The content of this article is about how PHP uses _call to implement multiple inheritance (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
This article briefly introduces the use of _call to achieve code reuse.
_call: A magic method of PHP. When a method that does not exist in the class is called, _call will be automatically called.
Sample code:
class One{ function method_1(){ echo '11<br/>'; } function method_2(){ echo '22<br/>'; } } class Two{ function method_3(){ echo '33<br/>'; } function method_4(){ echo '44<br/>'; } } class StaticDemo{ protected $Class = array(); public function __construct(array $class = array()){ $this->Class = $class; } public function __call($name, $arguments) { // TODO: Implement __call() method. foreach ($this->Class as $v){ if (is_callable(array($v, $name))) { //call_user_func_array在上篇文章中已作出理解 return call_user_func_array(array($v, $name), $arguments); } } return call_user_func_array(array($this, $name), $arguments); } } $obj = new StaticDemo(array(new One(), new Two())); $obj->method_1(); $obj->method_3();
Run Result: 11,33
The above is the detailed content of How to use _call to implement multiple inheritance in PHP (code example). For more information, please follow other related articles on the PHP Chinese website!