Instance as a static class property

后端 未结 2 1108
慢半拍i
慢半拍i 2021-01-12 06:11

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 $prop         


        
相关标签:
2条回答
  • 2021-01-12 06:56

    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.

    0 讨论(0)
  • 2021-01-12 06:58

    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();
    
    0 讨论(0)
提交回复
热议问题