gpt4 book ai didi

PHP 和闭包

转载 作者:行者123 更新时间:2023-12-02 07:08:59 27 4
gpt4 key购买 nike

我经常使用 JS,我开始喜欢闭包,所以我很高兴得知 PHP 中也有闭包。但是我就是不能让这些东西工作,这段代码有什么问题?

class Foo {
public $Bar;
public function Foo() {
$this->Bar = function() { echo "Hello World"; };
}
};

$F = new Foo();
$F->Bar();

我不断收到 PHP Fatal error: Call to undefined method Foo::Bar() 错误。

最佳答案

这已经在 SO 上进行了很多讨论(参见例如 this answer )。这应该可以解决问题:

$b = $f->Bar;
$b();

是的,就是这么蠢。你可以使用 call_user_func()放在一行中(参见 jlb's answer to this question ),但丑陋仍然存在。

关于PHP 和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7952735/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com