Tuesday, December 17, 2013

How to debug a class in php in run time? How to know the file name of the class defintion ?

Today's Class/Function: Reflection
The ReflectionClass class reports information about a class.

http://www.php.net/manual/en/class.reflectionclass.php

This class basically provides all the information about a particular class when executing the code.

How this is useful and where to use?

Lets say, We are working on a big framework and lot of classes are included in the execution. You may want to know what is the actual file a particular class has been defined ( to make changes or to check). You know only the class name.

If we track it manually, we need to check what are the files are included. The included files will then include many more files within themselves. So Its really difficult to find the actual file where a particular class resides.

This is where ReflectionClass is very useful.

Let me say, We are going to find the file where the class "SampleClass" defined.

<?php
$obj_reflector = new ReflectionClass('SampleClass');
echo "<br> File Name ".$obj_reflector->getFileName();
//Even you can find the line number where the class definition starts
echo "<br> Line Number ".$obj_reflector->getStartLine();
?>

Thats all, It will just echo the file name with its absolute path and line number defintion starts.

There are many other methods for this class which will be very useful for debugging purpose. You can check them here http://www.php.net/manual/en/class.reflectionclass.php

For example, with getMethod() method you can find information about a particular method in a class
<?php
$obj_reflector = new ReflectionClass('SampleClass');
echo $reflector->getMethod('sampleMethod');
?>

This will out something like below

Method [ final public method sampleMethod ] { @@ E:\MyFiles\www\sites\TestNetBeans\index.php 11 - 13

Sample code given below
<?
$test ="this is just some code";
$test ="this is just some code";
$test ="this is just some code";
$test ="this is just some code";
class SampleClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   final public function sampleMethod() {
       echo "BaseClass::moreTesting() called\n";
   }
}
$obj_reflector = new ReflectionClass('SampleClass');
echo '<br>File Name '.$obj_reflector->getFileName();
echo '<br>Line Number '.$obj_reflector->getStartLine();
echo '<br>'.$obj_reflector->getMethod('sampleMethod');
?>




No comments:

Post a Comment