2010-02-21 115 views

回答

0

可以實現這種功能與攔截__get()

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

儘管上一篇文章中的示例在將屬性更改爲public時也可以正常工作所以你可以從外面訪問它。

0

如果你的意思懶initalization,這是衆多方法之一:

class SomeClass 
{ 
    private $instance; 

    public function getInstance() 
    { 
     if ($this->instance === null) { 
      $this->instance = new AnotherClass(); 
     } 
     return $this->instance; 
    } 
} 
0
$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; 
    } 
}