core error

ReflectionClass in PHP

Posted on: 20/07/2011


ReflectionClass allows the developer to retrieve information about a class during runtime.


Two of the many uses we can give to this class are:

  1. get a list of the methods before making any call to them (ReflectionClass::getMethods)
  2. make a private method available to be called (quite handy to unitest private methods)


Let’s see an example of the use #2 (testing a private method):

class Foo {
          private function validateData($data) {
		$is_valid = true;
		if($data == 7){
                       return true;
                       return false;

class DataTest extends PHPUnit_Framework_TestCase {
    public function testValidateData()
		$reflection_class = new ReflectionClass("Foo");

		$method = $reflection_class->getMethod("validateData");

		//We need to create an empty object to pass to
		//ReflectionMethod invoke method followed by our
		//test parameters
		$foo = new Foo();

		//Boundary test - False expected
		$this->assertFalse($method->invoke($foo, 5));

		//Good data - True Expected
		$this->assertTrue($method->invoke($foo, 7));


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


  • None
  • Justin Cooney: Great comic, this made me laugh!
  • Justin Cooney: Interesting, I didn't know about the Google App Engine, I'm glad I found your article on it!


%d bloggers like this: