实例作为静态类属性

时间:2012-02-06 11:07:02

标签: php static

是否可以在PHP中将类的实例声明为属性?

基本上我想要达到的目标是:

abstract class ClassA() 
{
  static $property = new ClassB();
}

嗯,我知道我不能那样做,但除了总是做这样的事情之外还有其他解决方法:

if (!isset(ClassA::$property)) ClassA::$property = new ClassB();

3 个答案:

答案 0 :(得分:18)

你可以使用像单例一样的实现:

<?php
class ClassA {

    private static $instance;

    public static function getInstance() {

        if (!isset(self::$instance)) {
            self::$instance = new ClassB();
        }

        return self::$instance;
    }
}
?>

然后你可以用:

引用实例
ClassA::getInstance()->someClassBMethod();

答案 1 :(得分:4)

另一种解决方案,即静态构造函数,是

的基础
<?php
abstract class ClassA {
    static $property;
    public static function init() {
        self::$property = new ClassB();
    }
} ClassA::init();
?>

请注意,该课程不一定是抽象的。

另请参阅How to initialize static variableshttps://stackoverflow.com/a/3313137/118153

答案 2 :(得分:0)

这已经有几年了,但我遇到了一个问题,我有一个基类

class GeneralObject
{

    protected static $_instance;

    public static function getInstance()
    {
        $class = get_called_class();

        if(!isset(self::$_instance))
        {
            self::$_instance = new $class;
        }

        return self::$_instance;
    }
}

有一个子类

class Master extends GeneralObject 
{

}

还有另一个子类

class Customer extends Master 
{

}

但是当我尝试打电话时

$master = Master::getInstance();
$customer = Customer::getInstance();

那么 $master 将是 Master,正如预期的那样,但 $customer 将是 Master,因为 php 对 GeneralObject::$_instance 和 { 都使用了 Master {1}}

实现我想要的唯一方法是将 Customer 更改为 GeneralObject::$_instance 并调整 array 方法。

getInstance()

我希望这可以帮助其他人。我花了几个小时来调试发生了什么。

相关问题