简体   繁体   English

我们只能在类的构造函数中定义匿名函数吗?

[英]Can we only define anonymous function inside constructor of class?

<?php 
class Foo
{
    public $bar;
    public $var;

    public function __construct() {
        $this->bar = function() {
            return 42;
        };
    }

    public function test(){
        $this->var = function() {
            return 44;
        };
    }
}

$obj = new Foo();
echo ($obj->bar)(), "<br/>";
var_dump($obj->test());

?>

Output: 42 输出:42
NULL 空值

Where i am doing wrong I want to get var value inside test function which 44. 我在哪里做错了我想在测试函数里面获取var值44。

Thanks in advance for your answer. 预先感谢您的回答。

With this method call $obj->test() , you're just assigning a function to the instance variable $var . 使用此方法调用$obj->test() ,您只是将一个函数分配给实例变量$var And that's why when you do var_dump($obj->test()); 这就是为什么当您执行var_dump($obj->test()); , it shows NULL because the method doesn't return anything. ,则显示NULL因为该方法未返回任何内容。

Instead what you can do is, return $this from test() method and use the current instance to call that anonymous function, like this: 相反,您可以做的是,从test()方法返回$this ,并使用当前实例调用该匿名函数,如下所示:

class Foo{
    public $bar;
    public $var;

    public function __construct() {
        $this->bar = function() {
            return 42;
        };
    }

    public function test(){
        $this->var = function() {
            return 44;
        };
        return $this;
    }
}

$obj = new Foo();
echo ($obj->bar)(), "<br/>";
echo ($obj->test()->var)();

Here's the demo . 这是演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM