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

不言
Release: 2023-04-05 15:58:01
forward
2123 people have browsed it

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();
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template