Introduction to reflection of handwritten PHP API framework (3)
In the previous article "Handwritten PHP API Framework: Installation and Use of Composer (2)" we introduced the installation and use of Composer. In this article we will introduce the concept of reflection.
Reflection, intuitive understanding is to find the departure place and source based on the arrival place. Reflection refers to extending the analysis of PHP programs in the running state of PHP, exporting or proposing 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.
Let’s take a look at a demo first:
<?php function p($msg, $var) { echo($msg.":".print_r($var, true)).PHP_EOL.PHP_EOL; } class Demo { private $id; protected $name; public $skills = []; public function __construct($id, $name, $skills = []) { $this->id = $id; $this->name = $name; $this->skills = $skills; } public function getName() { return $this->name; } public function getSkill() { p('skill', $this->skills); } } $ref = new ReflectionClass('Demo'); if ($ref->isInstantiable()) { p('检查类是否可实例化isInstantiable', null); } $constructor = $ref->getConstructor(); p('获取构造函数getConstructor', $constructor); $parameters = $constructor->getParameters(); foreach ($parameters as $param) { p('获取参数getParameters', $param); } if ($ref->hasProperty('name')) { $attr = $ref->getProperty('name'); p('获取属性getProperty', $attr); } $attributes = $ref->getProperties(); foreach ($attributes as $row) { p('获取属性列表getProperties', $row->getName()); } if ($ref->hasMethod('getSkill')) { $method = $ref->getMethod('getSkill'); p('获取方法getMethod', $method); } $methods = $ref->getMethods(); foreach ($methods as $row) { p('获取方法列表getMethods', $row->getName()); } $instance = $ref->newInstanceArgs([1, 'sai', ['php', 'js']]); p('newInstanceArgs', $instance);
Output:
➜ php git:(main) php reflect.php 检查类是否可实例化isInstantiable: 获取构造函数getConstructor:ReflectionMethod Object ( [name] => __construct [class] => Demo ) 获取参数getParameters:ReflectionParameter Object ( [name] => id ) 获取参数getParameters:ReflectionParameter Object ( [name] => name ) 获取参数getParameters:ReflectionParameter Object ( [name] => skills ) 获取属性getProperty:ReflectionProperty Object ( [name] => name [class] => Demo ) 获取属性列表getProperties:id 获取属性列表getProperties:name 获取属性列表getProperties:skills 获取方法getMethod:ReflectionMethod Object ( [name] => getSkill [class] => Demo ) 获取方法列表getMethods:__construct 获取方法列表getMethods:getName 获取方法列表getMethods:getSkill newInstanceArgs:Demo Object ( [id:Demo:private] => 1 [name:protected] => sai [skills] => Array ( [0] => php [1] => js ) )
The ReflectionClass class is used in the demo. Of course, the ReflectionClass class is not limited to these methods.
More methods
The ReflectionClass class has more methods:
Method | Description |
---|---|
Initialize ReflectionClass Class | |
Export a class | |
Get the definition A constant | |
Get a set of constants | |
Get the constructor of the class | |
Get the default properties | |
Get documentation comments | |
Get the line number of the last line | |
Get the ReflectionExtension object of the extension based on the defined class | |
Get the name of the extension where the defined class is located | |
Get the file name of the definition class | |
Get Interface name | |
Get interface | |
Get the ReflectionMethod of a class method. | |
Get the array of methods | |
Get the class Modifiers | |
Get the class name | |
Get the name of the namespace | |
Get the parent class | |
Get a set of properties | |
Get the ReflectionProperty of a property of the class | |
Gets a ReflectionClassConstant for a class's constant | |
Gets class constants | |
Get the short name | |
Get the starting line number | |
Get static properties | |
Get the value of static properties | |
Returns an array of trait aliases | |
Returns An array of the names of traits used by this class | |
Returns an array of traits used by this class | |
Check whether the constant has been defined | |
Check whether the method has been defined | |
Check whether the property has been defined | |
Implementation of the interface | |
Check if it is in the namespace | |
Check if the class is abstract Class (abstract) | |
Check whether the class is an anonymous class | |
Returns whether a class can be copied | ##ReflectionClass::isFinal |
ReflectionClass::isInstance | |
ReflectionClass::isInstantiable | |
ReflectionClass::isInterface | |
ReflectionClass::isInternal | |
ReflectionClass::isIterable | |
ReflectionClass::isIterateable | |
ReflectionClass::isSubclassOf | |
ReflectionClass::isTrait | |
ReflectionClass::isUserDefined | |
ReflectionClass::newInstance | |
##ReflectionClass::newInstanceArgs | |
ReflectionClass::newInstanceWithoutConstructor | |
ReflectionClass:: setStaticPropertyValue | |
ReflectionClass::__toString | |
In addition to the powerful ReflectionClass, there are also Reflection, ReflectionClassConstant, ReflectionMethod, ReflectionFunctionAbstract and so on. It is recommended to check the manual: Practical Application of Reflection
Advantages of Reflection
Disadvantages of reflection
PHP Video Tutorial" |
The above is the detailed content of Introduction to reflection of handwritten PHP API framework (3). For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
