2010-02-21 117 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; 
    } 
}