当 PHP 类中引用实例变量时执行方法?
是否可以在引用 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
}
}
Is it possible to run a function when referring to a variable in a php class rather than simply returning its value, similar to javascript's ability for a variable to hold a method?
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP5 的魔术方法
__get($key)
和__set($key, $value)
可能正是您所需要的。有关它们的更多信息,请参阅 PHP 手册。PHP5s magic method
__get($key)
and__set($key, $value)
might be what you need. More information about them is available in the PHP manual.这听起来像 PHP5.3:lambda / 闭包 / 匿名函数
http://php.net/手册/en/functions.anonymous.php:
This sounds like PHP5.3: lambda / closures / anonymous functions
http://php.net/manual/en/functions.anonymous.php:
您可能正走向错误的方向。您通常需要定义一个 getter
getLazyVar()
。人们总是保护属性并定义 getter/setter 是有原因的:这样他们就可以对值进行预处理或后处理。You are probably heading in the wrong direction. You normally want to define a getter
getLazyVar()
. There is a reason why people always make properties protected and defined getters / setters: So they can pre- or postprocess the values.