Example of PHP reflection class ReflectionClass and ReflectionMethod

Source: Internet
Author: User
This article mainly introduces the PHP reflection class ReflectionClass and ReflectionMethod examples. This article also introduces what reflection is and what reflection can do, and provides a specific example, is a good entry

This article mainly introduces the PHP reflection class ReflectionClass and ReflectionMethod examples. This article also introduces what reflection is and what reflection can do, and provides a specific example, is a good entry

PHP5 has a complete reflection API to add reverse engineering capabilities for classes, interfaces, functions, methods, and extensions.

What is reflection?

It refers to the Extension Analysis of PHP programs in the PHP running state, exporting or extracting detailed information about classes, methods, attributes, parameters, and so on, including comments. This kind of dynamic information and the function of dynamically calling an object is called a reflection API. Reflection is an API used to manipulate the object-oriented model. It is very powerful and can help us build complex and scalable applications.

Its purpose is to automatically load plug-ins, generate documents automatically, and even expand the PHP language.

PHP reflection APIs are composed of several classes that can be used to access program metadata or interact with related annotations. With reflection, we can obtain methods implemented by the class, create an instance of the class (different from creating with new), call a method (also different from conventional call), and pass parameters, static Methods of the dynamic call class.
Reflection APIs are extensions of PHP built-in OOP technology, including some classes, exceptions, and interfaces. They can be used to help us analyze other classes, interfaces, methods, attributes, methods, and extensions. These OOP extensions are called reflection.

We usually use ReflectionClass and reflemethod method classes, for example:

The Code is as follows:


<? Php
Class Person {

/**
* For the sake of demonstration, we "re setting this private
*/
Private $ _ allowDynamicAttributes = false;

/**
* Type = primary_autoincrement
*/
Protected $ id = 0;

/**
* Type = varchar length = 255 null
*/
Protected $ name;

/**
* Type = text null
*/
Protected $ biography;

Public function getId (){
Return $ this-> id;
}

Public function setId ($ v ){
$ This-> id = $ v;
}

Public function getName (){
Return $ this-> name;
}

Public function setName ($ v ){
$ This-> name = $ v;
}

Public function getBiography (){
Return $ this-> biography;
}

Public function setBiography ($ v ){
$ This-> biography = $ v;
}
}

1. Through ReflectionClass, we can get the following information about the Person class:

1. Constant Contants
2. Property Names
3. Method Names static
4. Attribute Static Properties
5. Namespace
6. Whether the Person class is final or abstract
7. Does the Person class have a method?

Next, you only need to pass the class name "Person" to ReflectionClass:

The Code is as follows:


$ Class = new ReflectionClass ('person '); // creates a reflection class for the class "Person ".
$ Instance = $ class-> newInstanceArgs ($ args); // It is equivalent to instantiating the Person class

1) Properties ):

The Code is as follows:


$ Properties = $ class-> getProperties ();
Foreach ($ properties as $ property ){
Echo $ property-> getName (). "\ n ";
}
// Output:
// _ AllowDynamicAttributes
// Id
// Name
// Biography

By default, ReflectionClass obtains all attributes, and private and protected attributes can also be obtained. If you only want to get the private property, you need to pass an additional parameter:

The Code is as follows:


$ Private_properties = $ class-> getProperties (ReflectionProperty: IS_PRIVATE );

List of available parameters:

The Code is as follows:


ReflectionProperty: IS_STATIC
ReflectionProperty: IS_PUBLIC
ReflectionProperty: IS_PROTECTED
ReflectionProperty: IS_PRIVATE


You can get the property name through $ property-> getName.

2) get comments:

You can use getDocComment to get comments to the property.

The Code is as follows:


Foreach ($ properties as $ property ){
If ($ property-> isProtected ()){
$ Docblock = $ property-> getDocComment ();
Preg_match ('/type \ = ([a-z _] *)/', $ property-> getDocComment (), $ matches );
Echo $ matches [1]. "\ n ";
}
}
// Output:
// Primary_autoincrement
// Varchar
// Text

3) obtain the Class Method

The Code is as follows:


GetMethods () to obtain all the methods of the class.
HasMethod (string) whether a method exists
GetMethod (string)

4) Execution Methods:

The Code is as follows:


$ Instance-> getName (); // execute the getName method in Person
// Or:
$ Method = $ class-> getmethod ('getname'); // obtain the getName method in the Person class
$ Method-> invoke ($ instance); // execute the getName method
// Or:
$ Method = $ class-> getmethod ('setname'); // gets the setName method in the Person class.
$ Method-> invokeArgs ($ instance, array ('snsgou. com '));

2. Through ReflectionMethod, we can obtain information about a method of the Person class:

1. Whether it is of the "public", "protected", "private", or "static" Type
2. List of parameters of the Method
3. Number of parameters of the Method
4. Reverse call Method

The Code is as follows:


// Execute the detail method
$ Method = new ReflectionMethod ('person ', 'test ');

If ($ method-> isPublic ()&&! $ Method-> isStatic ()){
Echo 'Action is right ';
}
Echo $ method-> getNumberOfParameters (); // number of parameters
Echo $ method-> getParameters (); // array of parameter objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.