Home >Backend Development >PHP Tutorial >How to use _call to implement multiple inheritance in PHP (code example)

How to use _call to implement multiple inheritance in PHP (code example)

不言
不言forward
2019-03-15 13:19:272152browse

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 &#39;11<br/>&#39;;
    }
    function method_2(){
        echo &#39;22<br/>&#39;;
    }

}
class Two{
    function method_3(){
        echo &#39;33<br/>&#39;;
    }
    function method_4(){
        echo &#39;44<br/>&#39;;
    }
}
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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete