I am not sure if you will be able to fully understand why and how this is working at this point. You will need some experience with OOP
to get to the point where you realize and understand why you may need to use this.
Reflection
As you probably already know from the php documentation, the existence of get_class_methods
and get_class_vars
allows you to retrieve the class's methods and variables. Although you can just open the class and see the methods
and properties
for yourself, sometimes you might need to do it programmatically. Furthermore, you might want to change certain properties
or methods
and alter the behavior at runtime. This technique is referred as Reflection (Wiki , PHP).
When would I need to use Reflection?
As @mario mentioned in his comment:
- Developing modular platforms
- Developing certain complex tools
- Routing
- Reverse-engineering code
- Probably many other use cases I can't think of right now.
Examples?
You might find it easier to understand how things work if you have a look at the PHPUnit framework. It is a tool which provides the developers the ability to test their code via test cases. The test cases are usually stored in a class and every method tests a certain functionality. Here is an example test case class:
class UserTest extends \PHPUnit_Framework_TestCase {
public function testUserCreate(){
$firstName = "FirstName";
$lastName = "LastName";
$user = new User();
$user->setFirstName($firstName);
$user->setLastName($lastName);
assertEquals("FirstName", $user->getFirstName(), "Setting first name failed! Expected ".$firstName." but got ".$user->getFirstName()."!");
assertEquals("LastName", $user->getLastName(), "Setting last name failed! Expected ".$lastName." but got ".$user->getLastName()."!");
}
public function testUpdateUser(){ ... }
public function testDeleteUser(){ ... }
}
When PHPUnit is called and it starts executing the class above, all it will know about it would be the name of the class. PHPUnit will need to know the names of all public methods in that class so it could execute them. Therefore it will use the reflection technique to retrieve the methods of this class and then begin executing them one by one.
I hope this clarifies things.