设为首页 加入收藏

TOP

PHP通过_call实现多继承
2019-08-23 00:36:44 】 浏览:14
Tags:PHP 通过 _call 实现 继承
原文地址: http://small.aiweimeng.top/index.php/archives/53.html

上一篇讲到php可以通过接口是实现代码的复用。

那么这篇文章简单介绍下使用_call实现代码的复用。

_call:php的一个魔术方法,当调用类中不存在的method时,会自动调用_call.

示例代码:

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();

  

运行结果:11,33

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇PHP中的call_user_func()与call_u.. 下一篇laravel 的用户认证

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目