weixin

PHP的映射

日期: January 13, 2019 作者:网站维护

映射,就是就是观察或者说检查类。比如new一个映射类的对象,传入对象A作为参数。就可以给 A 做一次检查了,比如看看 A 有什么方法,有什么属性。

<?php
/**
 * Created by PhpStorm.
 * User: Ac
 * Date: 2019/1/13
 * Time: 22:17
 */
class ClassOne {
    function callClassOne()
    {
        print "In Class One\n";
    }
}

class ClassTwo {
    function callClassTwo(){
        print "In Class Two\n";
    }
}

class ClassOneDelegator {
    private $target;

    function __construct() {
        $this->target[] = new ClassOne();
    }

    function addObject($obj) {
        $this->target[] = $obj;
        var_dump($this);
    }

    function __call($name, $args){
        foreach ($this->target as $obj){
            $r = new ReflectionClass($obj);

            try {
                $method = $r->getMethod($name);
                if ($method->isPublic() && !$method->isAbstract()){
                    return $method->invoke($obj, $args);
                }
            } catch (Exception $e) {

            }
        }
    }
}

$obj = new ClassOneDelegator();
$obj->addObject(new ClassTwo());
$obj->callClassOne();
$obj->callClassTwo();

广告内容为平台自动生成