3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Hello2 { public function sayHello() { echo 'Hello '; } } class World2 { public function sayWorld() { echo 'World'; } } class MyHelloWorld2 { public $hello; public $world; public function __construct() { $this->hello = new Hello2(); $this->world = new World2(); } public function sayExclamationMark() { echo '!'; } public function __call($name, $arguments) { if (method_exists($this->hello, $name)) { var_dump('$this->hello->'.$name.'()'); // $this->hello->sayHello(); // 这个是可行的 // return $this->hello->sayHello(); // 这个就报错了 //return $this->hello->$name.'()'; return $this->hello->$name(); } if (method_exists($this->world, $name)) { // return $this->world->$name(); // 或者这样写 return call_user_func([$this->word, $name]); } if (!method_exists($this->hello, $name) && !method_exists($this->world, $name)) { echo '不存在此方法'; } } } $obj = new MyHelloWorld2(); $obj->sayHello(); $obj->sayWorld(); $obj->sayExclamationMark(); // 输出: // Hello World!

preferences:
51.68 ms | 402 KiB | 5 Q