Instance as a static class property

2019-02-21 17:57发布

Is it possible to declare an instance of a class as a property in PHP?

Basically what I want to achieve is:

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

Well, I know I can't do that, but is there any workaround beside always doing something like this:

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

标签: php static
2条回答
再贱就再见
2楼-- · 2019-02-21 18:24

you can use a singleton like implementation:

<?php
class ClassA {

    private static $instance;

    public static function getInstance() {

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

        return self::$instance;
    }
}
?>

then you can reference the instance with:

ClassA::getInstance()->someClassBMethod();
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-21 18:26

An alternative solution, a static constructor, is something along the lines of

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

Please note that the class doesn't have to be abstract for this to work.

See also How to initialize static variables and https://stackoverflow.com/a/3313137/118153.

查看更多
登录 后发表回答