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

Php 我们只能在类的构造函数中定义匿名函数吗?,php,Php,输出:42 空的 在我做错的地方,我想得到测试函数中的var值 提前感谢您的回答。使用此方法调用$obj->test(),您只需将一个函数分配给实例变量$var。这就是为什么当你做var_dump($obj->test()),它显示NULL,因为该方法不返回任何内容 相反,您可以从test()方法返回$this,并使用当前实例调用该匿名函数,如下所示: <?php class Foo { public $bar; public $var; public func

输出:42
空的

在我做错的地方,我想得到测试函数中的var值


提前感谢您的回答。

使用此方法调用
$obj->test()
,您只需将一个函数分配给实例变量
$var
。这就是为什么当你做
var_dump($obj->test())
,它显示
NULL
,因为该方法不返回任何内容

相反,您可以从
test()
方法返回
$this
,并使用当前实例调用该匿名函数,如下所示:

<?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());

?>
class-Foo{
公共酒吧;
公共价值$var;
公共函数构造(){
$this->bar=函数(){
返回42;
};
}
公共功能测试(){
$this->var=function(){
返回44;
};
退还$this;
}
}
$obj=新的Foo();
回声($obj->bar)(),“
”; echo($obj->test()->var)();

下面是。

使用此方法调用
$obj->test()
,您只需将一个函数分配给实例变量
$var
。这就是为什么当你做
var_dump($obj->test())
,它显示
NULL
,因为该方法不返回任何内容

相反,您可以从
test()
方法返回
$this
,并使用当前实例调用该匿名函数,如下所示:

<?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());

?>
class-Foo{
公共酒吧;
公共价值$var;
公共函数构造(){
$this->bar=函数(){
返回42;
};
}
公共功能测试(){
$this->var=function(){
返回44;
};
退还$this;
}
}
$obj=新的Foo();
回声($obj->bar)(),“
”; echo($obj->test()->var)();
这是。

$obj->test()
只是将函数关联到变量,它不会执行此函数。
$obj->test()
只是将函数关联到变量,它不会执行此函数。