Home > Backend Development > PHP Tutorial > Detailed description of reflection in php

Detailed description of reflection in php

韦小宝
Release: 2023-03-21 11:14:01
Original
1674 people have browsed it

This article talks about reflection in PHP. If you don’t know much about PHP reflection, you can take a look and understand it. This article briefly talks about reflection in PHP. Without further ado, let’s take a look!

PHP 5 has 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 TP framework

  • 1. ReflectionClass::__construct — Construct a ReflectionClass class

public ReflectionClass::__construct ( mixed $argument )
Copy after login

2. ReflectionClass::newInstanceArgs — Creates a new class instance from the given parameters, which will be passed to the constructor of the class.

public object ReflectionClass::newInstanceArgs ([ array $args ] )
Copy after login

3./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

This article briefly describes reflection in PHP. If you still don’t understand it, just practice and write it yourself. Write!


The above is the detailed content of Detailed description of reflection in php. 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