What is reflection in PHP? Detailed explanation of reflection usage examples

伊谢尔伦
Release: 2023-03-12 09:12:01
Original
1149 people have browsed it

Object-orientedObjects in editing are given the ability to introspect, and this introspection process is reflection.

Reflection, intuitive understanding, should find out the departure point and source according to the arrival place. For example, if I give you a bare object, I can know the class it belongs to and what methods it has just through this object.

Reflection refers to extending the analysis of the PHP program in the PHP running state and exporting Or extract detailed information about classes, methods, properties, parameters, etc., including comments. This function of dynamically obtaining information and dynamically calling object methods is called reflection API

How Using reflection API

Take the following code as an example

class HandsonBoy
{
    public $name = 'chenqionghe';
    public $age = 18;
    public function set($name,$value)
    {
        echo &#39;您正在设置私有属性&#39;.$name.&#39;<br >值为&#39;.$value.&#39;<br>&#39;;
        $this->$name = $value;
    }
    public function get($name)
    {
        if(!isset($this->$name))
        {
            echo &#39;未设置&#39;.$name;
            $this->$name = "正在为你设置默认值".&#39;<br>&#39;;
        }
        return $this->$name;
    }
}
$boy = new HandsonBoy();
echo $boy->name.&#39;<br />&#39;;
$boy->hair = &#39;short&#39;;
Copy after login

Now, what should we do to obtain the method and attribute list of this student object? It can be achieved using reflection, the code is as follows

$reflect = new ReflectionObject($boy);
$props = $reflect->getProperties();
//获取属性的名字
foreach($props as $prop)
{
    print $prop->getName().PHP_EOL;
}
//获取对象方法列表
$methos = $reflect->getMethods();
foreach($methos as $method)
{
    print $method->getName().PHP_EOL;
}
Copy after login

You can also use the class function instead of the reflection API to return an associative array of object properties and more information: (for public properties and):

//返回对象属性的关联数组
var_dump(get_object_vars($boy));
//类属性
var_dump(get_class_vars(get_class($boy)));
//返回由类的属性的方法名组成的数组
var_dump(get_class_methods(get_class($boy)));
Copy after login

The function of the reflection API is obviously more powerful , and can even restore the prototype of this class, including the access rights of the method. The following simply encapsulates the code of a printing class

/**
 * @param $classObject 对象或者类名
 */
function getClass($classObject)
{
    $object = new ReflectionClass($classObject);
    $className = $object->getName();
    $Methods = $Properties = array();
    foreach($object->getProperties() as $v)
    {
        $Properties[$v->getName()] = $v;
    }
    foreach($object->getMethods() as $v)
    {
        $Methods[$v->getName()] = $v;
    }
    echo "class {$className}\n{\n";
    is_array($Properties) && ksort($Properties);
    foreach($Properties as $k=>$v)
    {
        echo "\t";
        echo $v->isPublic() ? &#39;public&#39; : &#39;&#39;,$v->isPrivate() ? &#39;private&#39; :&#39;&#39;,$v->isProtected() ? &#39;protected&#39; : &#39;&#39;;
        $v->isStatic() ? &#39;static&#39; : &#39;&#39;;
        echo "\t{$k}\n";
    }
    echo "\n";
    if(is_array($Methods)) ksort($Methods);
    foreach($Methods as $k=>$v)
    {
        echo "\tfunction {$k}()\n";
    }
    echo "}\n";
}
Copy after login

Not only that, there are several details about the reflection API in the PHP Manual Ten, it can be said that reflection completely describes the prototype of a class or object. Reflection can be used not only for classes and objects, but also for functions, extension modules, exceptions, etc.

Reflection has What is the function

Reflection can be used to generate documents, so it can be used to scan the classes in the file and generate description documents one by one.

Since reflection can detect the internal structure of the class, then Can it be used as a hook to implement plug-in functions? Or as a dynamic proxy? To illustrate, the following code is a simple example

<?php
class mysql
{
    function connect($db)
    {
        echo "连接到数据库{$db[0]}".PHP_EOL;
    }
}
class sqlproxy
{
    private $target;
    public function construct($tar)
    {
        $this->target[] = new $tar;
    }
    public function call($name,$args)
    {
        foreach($this->target as $obj)
        {
            $r = new ReflectionClass($obj);
            if($method = $r->getMethod($name))
            {
                if($method->isPublic() && !$method->isAbstract())
                {
                    echo "方法前拦截记录LOG".PHP_EOL;
                    $method->invoke($obj,$args);
                    echo "方法后拦截".PHP_EOL;
                }
            }
        }
    }
}
$obj = new sqlproxy(&#39;mysql&#39;);
$obj->connect(&#39;chenqionghe&#39;);
Copy after login

The real operating class here is the mysql class, but sqlproxy implements dynamic incoming Parameters, running instead of the actual class, intercepting before and after the method is run, and dynamically changing the methods and properties in the class. This is a simple dynamic proxy.

Where reflection is used in normal development There are not many: one is to debug the object, and the other is to obtain class information. In MVC and plug-in development, using reflection is very common, but reflection is also very expensive, and alternatives can be found. In this case, do not abuse it.

PHP has the Token function, which can implement some reflection functions through this mechanism. From a simple and flexible perspective, it is advisable to use the reflection API that has been provided.

Many times, making good use of reflection can keep the code elegant and concise, but reflection can also destroy the encapsulation of the class, because reflection can force methods or properties that should not be exposed to be exposed, which is both an advantage and a disadvantage.

The above is the detailed content of What is reflection in PHP? Detailed explanation of reflection usage examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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