【问题标题】:How to implement this feature in PHP?如何在 PHP 中实现此功能?
【发布时间】:2010-02-21 16:12:57
【问题描述】:

当访问不 存在,自动创建 对象。

$obj = new ClassName();
$newObject = $ojb->nothisobject;

有可能吗?

【问题讨论】:

    标签: php class accessor


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      你可以使用 Interceptor __get() 来实现这种功能

      class ClassName
      {
      function __get($propertyname){
      $this->{$propertyname} = new $propertyname();
      return $this->{$propertyname}
      }
      }
      

      虽然上一篇文章中的示例在属性更改为公共时也可以正常工作,因此您可以从外部访问它。

      【讨论】:

        【解决方案3】:

        如果您的意思是惰性初始化,这是多种方式之一:

        class SomeClass
        {
            private $instance;
        
            public function getInstance() 
            {
                if ($this->instance === null) {
                    $this->instance = new AnotherClass();
                }
                return $this->instance;
            }
        }
        

        【讨论】:

          【解决方案4】:
          $obj = new MyClass();
          
          $something = $obj->something; //instance of Something
          

          使用以下延迟加载模式:

          <?php
          
          class MyClass
          {
              /**
               * 
               * @var something
               */
              protected $_something;
          
              /**
               * Get a field
               *
               * @param  string $name
               * @throws Exception When field does not exist
               * @return mixed
               */
              public function __get($name)
              {
                  $method = '_get' . ucfirst($name);
          
                  if (method_exists($this, $method)) {
                      return $this->{$method}();
                  }else{
                      throw new Exception('Field with name ' . $name . ' does not exist');
                  }
              }
          
              /**
               * Lazy loads a Something
               * 
               * @return Something
               */
              public function _getSomething()
              {
                  if (null === $this->_something){
                      $this->_something = new Something();
                  }
          
                  return $this->_something;
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-08-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多