0

我已经实现了一个单例模式类,并且可以在这样的其他类中使用:

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 ? 

    }

} 
4

2 回答 2

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时的(),它是一个方法,而不是一个成员。

于 2013-04-11T19:01:27.900 回答
0

$sngtAttr 是静态属性吗?

如果没有,那么只是:
echo $this->attr->sngtAttr; instead of echo $this->attr::$sngtAttr; 会这样做。

否则因为是静态的:

echo Singleton::$sngtAttr;

于 2013-04-11T18:59:57.033 回答