调用在 php 中定义为对象变量的匿名函数 [英] Calling anonymous functions defined as object variables in php
本文介绍了调用在 php 中定义为对象变量的匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的 php 代码:
I have php code like:
class Foo {
public $anonFunction;
public function __construct() {
$this->anonFunction = function() {
echo "called";
}
}
}
$foo = new Foo();
//First method
$bar = $foo->anonFunction();
$bar();
//Second method
call_user_func($foo->anonFunction);
//Third method that doesn't work
$foo->anonFunction();
在php中有没有办法可以使用第三种方法来调用定义为类属性的匿名函数?
Is there a way in php that I can use the third method to call anonymous functions defined as class properties?
谢谢
推荐答案
不是直接的.$foo->anonFunction();
不起作用,因为 PHP 会尝试直接调用该对象上的方法.它不会检查是否存在存储可调用的名称的属性.不过你可以拦截方法调用.
Not directly. $foo->anonFunction();
does not work because PHP will try to call the method on that object directly. It will not check if there is a property of the name storing a callable. You can intercept the method call though.
将此添加到类定义
public function __call($method, $args) {
if(isset($this->$method) && is_callable($this->$method)) {
return call_user_func_array(
$this->$method,
$args
);
}
}
在
这篇关于调用在 php 中定义为对象变量的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文