首页 > 解决方案 > call_user_func_array 和 __call 创建无限循环

问题描述

我有一个class Aandclass 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了。但是如果我helloclass A

这是预期的行为吗?我能做些什么来防止这种情况发生吗?

标签: phpcall-user-func-array

解决方案


数组解构需要 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

推荐阅读