Home  >  Article  >  Backend Development  >  PHP reflection mechanism explained

PHP reflection mechanism explained

小云云
小云云Original
2018-03-14 09:54:591562browse

PHP 5 features a complete reflection API, adding the ability to reverse engineer classes, interfaces, functions, methods, and extensions. Additionally, the Reflection API provides methods to extract documentation comments from functions, classes, and methods.

The use of reflection in the tp framework:

  • ReflectionClass::__construct — Construct a ReflectionClass class

public ReflectionClass::__construct ( mixed $argument )
  • ReflectionClass::newInstanceArgs — Creates a new class instance from the given arguments, which are passed to the class's constructor.

public object ReflectionClass::newInstanceArgs ([ array $args ] )
  • /thinkphp/library/think/Container.php

 /**
     * 调用反射执行类的实例化 支持依赖注入
     * @access public
     * @param  string    $class 类名
     * @param  array     $vars  参数
     * @return mixed
     */
    public function invokeClass($class, $vars = [])
    {
        try {            $reflect = new ReflectionClass($class);            $constructor = $reflect->getConstructor();            //用于支持依赖的注入
            $args = $constructor ? $this->bindParams($constructor, $vars) : [];            return $reflect->newInstanceArgs($args);
        } catch (ReflectionException $e) {            throw new ClassNotFoundException('class not exists: ' . $class, $class);
        }
    }

Related recommendations:

Detailed explanation of the php reflection method calling the private method in the execution class

Brief description of the php reflection mechanism example and detailed explanation

Detailed explanation of the php reflection mechanism And detailed explanation of plug-in architecture examples

The above is the detailed content of PHP reflection mechanism explained. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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