【问题标题】:Instance as a static class property实例作为静态类属性
【发布时间】:2012-02-06 11:07:01
【问题描述】:

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

基本上我想要实现的是:

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

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

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

【问题讨论】:

标签: php static


【解决方案1】:

您可以使用类似单例的实现:

<?php
class ClassA {

    private static $instance;

    public static function getInstance() {

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

        return self::$instance;
    }
}
?>

然后你可以引用实例:

ClassA::getInstance()->someClassBMethod();

【讨论】:

  • 我宁愿不叫它getInstance,而是叫getB()。
【解决方案2】:

另一种解决方案,静态构造函数,类似于

<?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

【讨论】:

    【解决方案3】:

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

    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 对MasterCustomer 都使用GeneralObject::$_instance

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

    class GeneralObject
    {
    
        protected static $_instance = array();
    
        public static function getInstance()
        {
            $class = get_called_class();
    
            if(!isset(self::$_instance[$class]))
            {
                self::$_instance[$class] = new $class;
            }
    
            return self::$_instance[$class];
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 2013-08-25
      • 2017-09-05
      相关资源
      最近更新 更多