当指参考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
    }

}
有帮助吗?

解决方案

这听起来像php5.3:lambda / closures /匿名函数

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

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

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

其他提示

PHP5S魔法方法 __get($key)__set($key, $value) 可能是您需要的。有关它们的更多信息可在 PHP手册.

您可能朝错误的方向前进。您通常想定义一个getter getLazyVar(). 。人们始终始终保护属性和定义的Getters / Setter是有原因的:因此他们可以预先或后处理值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top