我已经实现了一个单例模式类,谁可以在其他类中使用:
class myClass {
private $attr;
public function __construct() {
$this->attr = Singleton::getInstance;
echo $this->attr::$sngtAttr; // Throw an error
// witch syntax use whithout pass by a temp var ?
}
}
答案 0 :(得分:0)
$ sngtAttr是静态属性吗?
如果没有,那么只是:
echo $this->attr->sngtAttr; instead of echo $this->attr::$sngtAttr;
会做的。
否则因为是静态的:
echo Singleton::$sngtAttr;
答案 1 :(得分:0)
你的问题到底是什么? 这就是你做单身人士的方式:
<?php
class ASingletonClass
{
// Class unique instance. You can put it as a static class member if
// if you need to use it somewhere else than in yout getInstance
// method, and if not, you can just put it as a static variable in
// the getInstance method.
protected static $instance;
// Constructor has to be protected so child classes don't get a new
// default constructor which would automatically be public.
protected final function __construct()
{
// ...
}
public static function getInstance()
{
if( ! isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
// OR :
public static function getInstance()
{
static $instance;
if( ! isset($instance)) {
$instance = new self;
}
return $instance;
// In that case you can delete the static member $instance.
}
public function __clone()
{
trigger_error('Cloning a singleton is not allowed.', E_USER_ERROR);
}
}
?>
当你调用getInstance时也不要忘记(),它是一个方法,而不是成员。