我正在为网站使用单例模式,因此用户需要能够注册。我希望能够在许多函数中使用相同的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
,因此不会检查链接状态
这有什么问题?
我没有收到任何错误,并在
上报告错误答案 0 :(得分:1)
已经尝试过你的代码,但似乎工作正常。我添加了一些var转储并查看输出:
print
输出:
<?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);
看起来像是预期的还是我错过了什么?