2011-01-12 67 views
0

有没有可能在php类中引用变量时运行函数,而不是简单地返回它的值,类似于javascript的变量持有方法的能力?在PHP类中引用实例变量时执行方法吗?

class LazyClassTest() 
{ 

    protected $_lazyInitializedVar; 

    public function __construct() 
    { 
     /* // How can this call and return runWhenReferrenced() when 
      // someone refers to it outside of the class: 
      $class = new LazyClass(); 
      $class->lazy; 
      // Such that $class->lazy calls $this->runWhenReferrenced each 
      // time it is referred to via $class->lazy? 
     */ 
     $this->lazy = $this->runWhenReferrenced(); 
    } 

    protected function runWhenReferrenced() 
    { 
     if (!$this->_lazyInitializedVar) { 
      $this->_lazyInitializedVar = 'someValue'; 
     } 

     return $this->_lazyInitializedVar 
    } 

} 

回答

2

PHP5s魔术方法__get($key)__set($key, $value)可能是你所需要的。有关它们的更多信息,请参见PHP manual

+0

嗯......我们并非人人懂德语,那么为什么不分享英文说明书? :-) – Rafid 2011-01-12 16:16:11

+0

对不起,修正了链接。 – mplappert 2011-01-12 16:19:20

1

您可能正朝着错误的方向前进。您通常要定义一个吸气剂getLazyVar()。为什么人们总是对属性进行保护并定义getter/setter:这是有原因的:所以他们可以对这些值进行预处理或后处理。