PHP reflection mechanism explained

小云云
Release: 2023-03-21 11:00:02
Original
1523 people have browsed it

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 )
Copy after login
  • 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 ] )
Copy after login
  • /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);
        }
    }
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!