__call,__callStatic 方法拦截器事件委托

<?php
// 事件委托
class Base 
{
    public function write(...$args)
    {
        printf('方法名: %s(), 参数 [%s]',__METHOD__, implode(', ', $args));
    }

    public static function fetch(...$args)
    {
        printf('方法名: %s(), 参数 [%s]',__METHOD__, implode(', ', $args));
    }
}

// 工做类
class Work
{
    // 事件委托时,重定向到的类
    private $base;

    // 将$base初始化
    public function __construct(Base $base)
    {
        $this->base = $base;
    }

    // 方法拦截器,将$this->write()重定向到$this->base->write()
    public function __call($name, $args)
    {
        // 将$this->$name()重  定向到$this->base->$name()
        if (method_exists($this->base, $name))
        // return $this->base->$name($name, $args);
        //使用call_user_func_array()函数回调对象中的成员方法,第一个参数应该使用数组的方式: [对象引用, '对象中的方法名']
        return call_user_func_array([$this->base, 'write'], $args);
    }

    // 方法拦截器,将self::fetch()重定向到Base::fetch()
    public static function __callStatic($name, $args)
    {
        if (method_exists('Base', $name))
        //使用call_user_func_array()函数回调类中的静态成员方法,第一个参数应该使用数组的方式: [类名称, '类中静态方法名称']
        return call_user_func_array(['Base', 'fetch'], $args);
    }
}


$base = new Base();

$work = new Work($base);

$work->write(1,2,3);

$work::fetch('abc', 'ppp', 'www');
相关文章
相关标签/搜索