gpt4 book ai didi

类实例上的 PHP 闭包

转载 作者:可可西里 更新时间:2023-11-01 00:45:21 25 4
gpt4 key购买 nike

如果我有这样的类(class):

class MyClass
{
public function foo()
{
echo "foo";
}
}

然后在类之外实例化它并尝试在其中创建一个匿名函数:

$mine = new MyClass();

$mine->bar = function() {
echo "bar";
}

然后尝试像 $mine->bar() 那样调用它,我得到:

Fatal error: Call to undefined method MyClass::bar() in ...

如何在类实例上创建匿名函数/闭包?

旁白:在你告诉我我应该重新考虑我的逻辑或正确使用接口(interface)和 OOP 之前,在我的例子中,它是一个方便的方法,适用于这个 SCSS 类的特定实例,试图清理一个遗留程序应用程序。是的,我使用的是 PHP 5.3+

最佳答案

在这里查看我的博客文章:http://blog.flowl.info/2013/php-container-class-anonymous-function-lambda-support/

你需要加个魔法__call功能:

public function __call($func, $args) {
return call_user_func($this->$func, $args);
}

问题在于,在此构造中,您可以从公共(public)范围调用私有(private)方法。我建议不要简单地将新变量添加到未定义的类中。您可以使用神奇的 __set 函数和 catch 容器中的所有 undefined variable (= 数组,就像我的博客文章中那样)来避免这种情况,并将 call_user_func 行为更改为仅在数组:

// inside class:
public $members = array();

public function __call($func, $args) {
// note the difference of calling only inside members:
return call_user_func($this->members[$func], $args);
}

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

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