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

发布于 2024-10-11 12:30:08 字数 817 浏览 11 评论 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
    }

}

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瑶笙 2024-10-18 12:30:08

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.

貪欢 2024-10-18 12:30:08

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

http://php.net/手册/en/functions.anonymous.php

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

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

This sounds like 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');
?>
决绝 2024-10-18 12:30:08

您可能正走向错误的方向。您通常需要定义一个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文