0

我有一个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

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

4

2 回答 2

0

数组解构需要 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
于 2019-05-19T00:33:17.213 回答
0

玩了一段时间后,您似乎可以将 hello 函数设置为受保护而不是私有。

您的代码有几个小问题。看评论。

class A {
  public function __call($name, $params) {
    if (method_exists($this, "{$name}")) {
      $this->before();
      $result = call_user_func_array([$this, "{$name}"], $params);
      $this->after();
      return $result;
    }
  }
  private function before() {
    echo "before\n";
  }
  private function after() {
    echo "after\n";
  }
}

class B extends A {
  protected function hello() {
    echo "Hello\n";
  }
}

$b = new B();
$b->hello();

当我运行它时,这是我得到的结果。

before
Hello
after

我在 PHP 7.0.8 上运行它。

简短回答:父类中的公共方法不能调用子类中的私有方法。

您也可以使用特征。

trait Wrappable
{
  public function __call($name, $params) {
    if (method_exists($this, $name)) {
      $this->before();
      $result = call_user_func_array([$this, $name], $params);
      $this->after();
      return $result;
    }
  }
  private function before() {
    echo "before\n";
  }
  private function after() {
    echo "after\n";
  }

}

class A {

  use Wrappable;

  public function pub()
  {
    echo __METHOD__ . "\n";
  }

}

class B {
  use Wrappable;
  protected function hello() {
    echo "Hello\n";
  }

  protected function protHello()
  {
    echo __METHOD__ . "\n";
    $this->privHello();
  }
  protected function visibilityBridge($f, $a)
  {

  }
  private function privHello()
  {
    echo __METHOD__ . "\n";
  }
}
$a = new A();
$a->pub();
$b = new B();
$b->privHello();
于 2019-05-18T23:30:55.800 回答