php - call_user_func_array 和 __call 创建无限循环
问题描述
我有一个class A
andclass B
继承自class A
,我想在运行函数之前运行一些检查。
class A {
public class __call($name, $params) {
if (method_exists?($this, $name)) {
$result = call_user_func_array([$this, $name], $params);
return $result;
}
}
}
class B {
private function hello() {
echo "Hello"
}
}
当我打电话时,我期待着:
$b = new B();
$b->hello();
它会调用__call
然后执行private function hello
,但它开始无限循环,看起来又call_user_func_array
触发__call
了。但是如果我hello
在class A
这是预期的行为吗?我能做些什么来防止这种情况发生吗?
解决方案
数组解构需要 PHP 7+。
class A {
public function __call($name, $params) { //this is a function
if (method_exists($this, $name)) { // Remove ?
$result = $this->$name(...$params); //Really calls the function from the context
return $result;
}
// As a suggestion you should throw an exception here for maintainability
}
}
class B extends A { // You need 'extends A'
private function hello() {
echo "Hello"; // ;
}
}
$b = new B();
$b->hello(); // Hello
推荐阅读
- scrapy - 尝试在不启动scrapy项目但从 .py 文件的情况下下载文件。在 python 文件中创建了自定义管道,这个错误是提到的
- jenkins - Jenkins miniOrange SAML 2.0 登录失败
- pine-script - pinescript 中的脚本警报
- netlify-function - cloudconvert API 不适用于 netlify 无服务器功能
- python - 在由三个或更多零分隔的部分中对列表元素进行计数和求和
- github - 没有合并的 PR 验证管道
- javascript - Spotify WebApi 无法获取用户播放列表数据
- css - 为什么我的 CSS 中的椭圆形 div 在我调整大小或还原它时会放在我网站的右侧墙(边框)旁边?
- javascript - Angular 10 与现有 PHP 项目的集成
- javascript - 引导多选搜索栏中的默认值选择未显示