使用singleton模式来拥有多个创建者


Using singleton pattern to have multiple creators

我正在为站点使用singleton模式,为此用户需要能够注册。我希望能够在许多函数中使用相同的Init()函数,并想知道实现这一点的最佳方法。

到目前为止,我所拥有的是:

<?php
class User
{
    public static $username;
    public static $email;
    private static $init;
    private static $link;
    private function __construct() 
    {
        if (!static::$link)
        {
            global $link;
            if (isset($link))
                static::$link = $link;
            else
                die("Failed to get link.");
            return;
        }
        return;
    }
    /**
     * @return User
     */
    public static function Init()
    {
        return static::$init = (
                null === static::$init ? new self() : static::$init
            );
    }
    public static function Register($username, $password, $email, $role)
    {
        return static::Init(); /* Only returning this for testing purposes */
    }
}

我已经对此进行了测试,$user = User::Init()调用可以工作,但由于某种原因,静态函数Register在运行时不会进入专用__construct,因此不会检查链接状态。

这有什么问题?

我没有收到任何错误,并且在上有错误报告

已经试用了您的代码,但它似乎运行良好。我添加了一些var转储,并看到了输出:

<?php
class User
{
    public static $username;
    public static $email;
    private static $init;
    private static $link;
    private function __construct() 
    {
        var_dump(__CLASS__ . ' in method ' . __FUNCTION__ );
        if (!static::$link)
        {
            global $link;
            if (isset($link))
                static::$link = $link;
            else
                die("Failed to get link.");
            return;
        }
        return;
    }
    /**
     * @return User
     */
    public static function Init()
    {
        var_dump(__CLASS__ . ' in method ' . __FUNCTION__ );
        return static::$init = (
                null === static::$init ? new self() : static::$init
            );
    }
    public static function Register($username, $password, $email, $role)
    {
        var_dump(__CLASS__ . ' in method ' . __FUNCTION__ );
        return static::Init(); /* Only returning this for testing purposes */
    }
}
$link = true; // dummy var to satisfy your __construct method
$user = User::Register(1,2,3,4);

输出:

string 'User in method Register' (length=23)
string 'User in method Init' (length=19)
string 'User in method __construct' (length=26)

看起来像是意料之中的事,还是我错过了什么?