在PHP类中引用实例变量时执行方法?

时间:2011-01-12 16:08:59

标签: php oop class lazy-initialization

是否可以在引用php类中的变量时运行函数而不是简单地返回其值,类似于javascript的变量保存方法的能力?

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
    }

}

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

你可能正走向错误的方向。您通常要定义一个getter getLazyVar()。人们总是保护属性并定义getter / setter是有原因的:因此他们可以对值进行预处理或后处理。

答案 2 :(得分:1)

这听起来像PHP5.3:lambda / closures / anonymous functions

http://php.net/manual/en/functions.anonymous.php

<?php
$greet = function($name) {
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>