0

是否可以在引用 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
    }

}
4

3 回答 3

2

PHP5s 魔术方法__get($key)__set($key, $value)可能是你需要的。PHP 手册中提供了有关它们的更多信息。

于 2011-01-12T16:11:56.673 回答
1

您可能正朝着错误的方向前进。您通常想要定义一个 getter getLazyVar()。人们总是将属性设置为受保护和定义的 getter/setter 是有原因的:因此他们可以对值进行预处理或后处理。

于 2011-01-12T16:17:27.943 回答
1

这听起来像 PHP5.3:lambda / 闭包 / 匿名函数

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

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

$greet('World');
$greet('PHP');
?>
于 2011-01-12T17:00:26.237 回答