PHP reflection class ReflectionClass and ReflectionObject
PHP reflection class ReflectionClass and ReflectionObject
PHP extension reflection class, which is used to analyze php programs, export or extract detailed information about classes, methods, attributes, parameters, and so on, including comments.
Let's look at this question. The member variables of the php class are not declared in the class, but in the function. What is the difference?
The Code is as follows:
Class test {
Private $ name;
Private $ sex;
Function _ construct (){
$ This-> aaa = 'aaa ';
}
}
$ Test = new test ();
$ Reflect = new ReflectionClass ($ test );
$ Pro = $ reflect-> getDefaultProperties ();
Print_r ($ pro); // print the result: Array ([name] => [sex] =>)
Echo $ test-> aaa; // print the result: aaa
In this test class, two member variables $ name and $ sex are declared, but in the constructor, another variable $ aaa is declared, and the class is initialized, using the reflection class to print the default member attribute only has two declared member variable attributes, but the $ aaa variable of the print class can still be output.
Do I have to declare the member variables of the class? Can I declare them in the function? What is the difference?
In your example, using ReflectionClass is inappropriate, because _ construct is executed only when class is instantiated.
That is to say, ReflectionClass is more about the structure during reflection class declaration than the structure after class instantiation. Therefore, it is true that no output attribute aaa is correct because the attribute aaa is indeed (during class Declaration) does not exist.
In this case, attributes aaa should be reflected in the instantiated structure using ReflectionObject, for example
The Code is as follows:
Class test {
Private $ name;
Private $ sex;
Function _ construct (){
$ This-> aaa = 'aaa ';
}
}
$ Test = new test ();
$ Reflect = new ReflectionObject ($ test );
$ Pro = $ reflect-> getProperties ();
Print_r ($ pro );
After instantiation, the property aaa will exist, and you will be able to see the property aaa.
Because php is a "dynamic" language, you do not need to declare the member variables of A Class. It is also possible to declare them in functions.