首頁  >  文章  >  後端開發  >  PHP反射機制詳解

PHP反射機制詳解

小云云
小云云原創
2018-03-20 13:33:273308瀏覽

本文主要和大家分享PHP反射機制詳解,內容包括1.自動產生文件2.實現 MVC 架構3.實現單元測試4.配合 DI 容器解決依賴,希望能幫助大家。

1.自動產生文件

根據反射的分析類,接口,函數和方法的內部結構,方法和函數的參數,以及類別的屬性和方法,可以自動產生文檔。

<?phpclass Student{
    const NORMAL = 1;    const FORBIDDEN = 2;    /**
     * 用户ID
     * @var 类型
     */
    public $id;    /**
     * 获取id
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }    public function setId($id = 1)
    {
        $this->id = $id;
    }
}$ref = new ReflectionClass(&#39;Student&#39;);$doc = $ref->getDocComment();echo $ref->getName() . &#39;:&#39; . getComment($ref) , "<br/>";echo "属性列表:<br/>";
printf("%-15s%-10s%-40s<br/>", &#39;Name&#39;, &#39;Access&#39;, &#39;Comment&#39;);$attr = $ref->getProperties();foreach ($attr as $row) {
    printf("%-15s%-10s%-40s<br/>", $row->getName(), getAccess($row), getComment($row));
}echo "常量列表:<br/>";
printf("%-15s%-10s<br/>", &#39;Name&#39;, &#39;Value&#39;);$const = $ref->getConstants();foreach ($const as $key => $val) {
    printf("%-15s%-10s<br/>", $key, $val);
}echo "<br/><br/>";echo "方法列表<br/>";
printf("%-15s%-10s%-30s%-40s<br/>", &#39;Name&#39;, &#39;Access&#39;, &#39;Params&#39;, &#39;Comment&#39;);$methods = $ref->getMethods();foreach ($methods as $row) {
    printf("%-15s%-10s%-30s%-40s<br/>", $row->getName(), getAccess($row), getParams($row), getComment($row));
}// 获取权限function getAccess($method){
    if ($method->isPublic()) {        return &#39;Public&#39;;
    }    if ($method->isProtected()) {        return &#39;Protected&#39;;
    }    if ($method->isPrivate()) {        return &#39;Private&#39;;
    }
}// 获取方法参数信息function getParams($method){
    $str = &#39;&#39;;    $parameters = $method->getParameters();    foreach ($parameters as $row) {        $str .= $row->getName() . &#39;,&#39;;        if ($row->isDefaultValueAvailable()) {            $str .= "Default: {$row->getDefaultValue()}";
        }
    }    return $str ? $str : &#39;&#39;;
}// 获取注释function getComment($var){
    $comment = $var->getDocComment();    // 简单的获取了第一行的信息,这里可以自行扩展
    preg_match(&#39;/\* (.*) *?/&#39;, $comment, $res);    return isset($res[1]) ? $res[1] : &#39;&#39;;
}

輸出結果:

Student:
属性列表:
Name Access Comment 
id Public 用户ID 
常量列表:
Name Value 
NORMAL 1 FORBIDDEN 2 方法列表
Name Access Params Comment 
getId Public 获取id 
setId Public id,Default: 1

2.實作MVC 架構

現在好多框架都是MVC 的架構,根據路由資訊定位控制器($controller) 和方法( $method) 的名稱,之後使用反射實作自動呼叫。

$class = new ReflectionClass(ucfirst($controller) . &#39;Controller&#39;);$controller = $class->newInstance();if ($class->hasMethod($method)) {    $method = $class->getMethod($method);    $method->invokeArgs($controller, $arguments);
} else {
    throw new Exception("{$controller} controller method {$method} not exists!");
}

3.實現單元測試

一般情況下我們會對函數和類別進行測試,判斷其是否能夠按我們預期返回結果,我們可以用反射實現一個簡單通用的類測試用例。

<?phpclass Calc{
    public function plus($a, $b)
    {
        return $a + $b;
    }    public function minus($a, $b)
    {
        return $a - $b;
    }
}function testEqual($method, $assert, $data){
    $arr = explode(&#39;@&#39;, $method);    $class = $arr[0];    $method = $arr[1];    $ref = new ReflectionClass($class);    if ($ref->hasMethod($method)) {        $method = $ref->getMethod($method);        $res = $method->invokeArgs(new $class, $data);        if($res === $assert){            echo "测试结果正确";
        };
    }
}
testEqual(&#39;Calc@plus&#39;, 3, [1, 2]);echo  "<br/>";
testEqual(&#39;Calc@minus&#39;, -1, [1, 2]);

這是類別的測試方法,也可以利用反射實作函數的測試方法。

<?phpfunction title($title, $name){
    return sprintf("%s. %s\r\n", $title, $name);
}$function = new ReflectionFunction(&#39;title&#39;);echo $function->invokeArgs(array(&#39;Dr&#39;, &#39;Phil&#39;));?>

這裡只是我簡單寫的一個測試案例,PHPUnit 單元測試框架很大程度上依賴了 Reflection 的特性,可以了解下。

4.配合 DI 容器解決依賴

Laravel 等許多框架都是使用 Reflection 解決依賴注入問題,具體可查看 Laravel 原始碼進行分析。
下面我們程式碼簡單實作一個 DI 容器示範 Reflection 解決依賴注入問題。

<?phpclass DI{
    protected static $data = [];    public function __set($k, $v)
    {
        self::$data[$k] = $v;
    }    public function __get($k)
    {
        return $this->bulid(self::$data[$k]);
    }    // 获取实例
    public function bulid($className)
    {
        // 如果是匿名函数,直接执行,并返回结果
        if ($className instanceof Closure) {            return $className($this);
        }        // 已经是实例化对象的话,直接返回
        if(is_object($className)) {            return $className;
        }        // 如果是类的话,使用反射加载
        $ref = new ReflectionClass($className);        // 监测类是否可实例化
        if (!$ref->isInstantiable()) {            throw new Exception(&#39;class&#39; . $className . &#39; not find&#39;);
        }        // 获取构造函数
        $construtor = $ref->getConstructor();        // 无构造函数,直接实例化返回
        if (is_null($construtor)) {            return new $className;
        }        // 获取构造函数参数
        $params = $construtor->getParameters();        // 解析构造函数
        $dependencies = $this->getDependecies($params);        // 创建新实例
        return $ref->newInstanceArgs($dependencies);
    }    // 分析参数,如果参数中出现依赖类,递归实例化
    public function getDependecies($params)
    {
        $data = [];        foreach($params as $param)
        {            $tmp = $param->getClass();            if (is_null($tmp)) {                $data[] = $this->setDefault($param);
            } else {                $data[] = $this->bulid($tmp->name);
            }
        }        return $data;
    }    // 设置默认值
    public function setDefault($param)
    {
        if ($param->isDefaultValueAvailable()) {            return $param->getDefaultValue();
        }        throw new Exception(&#39;no default value!&#39;);
    }
}class Demo{
    public function __construct(Calc $calc)
    {
        echo $calc->plus(1, 2);
    }
}class Calc{
    public function plus($a, $b)
    {
        return $a + $b;
    }    public function minus($a, $b)
    {
        return $a - $b;
    }
}$di = new DI();$di->calc = &#39;Calc&#39;;  
$di->demo = &#39;Demo&#39;;$di->demo;//输出结果为3

相關推薦:

php反射機制解說

#簡述php反射機制實例詳解

php反射機制實作外掛程式的設計實例詳解

#

以上是PHP反射機制詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn