3 minutes to read, 5.78K views since 2016.10.13 Читать на русском

Get all information about some class in compact form using reflection

Today i'm going to show you how you can get all possible information about class in php using Reflection Api.

At first lets create class we going to analyze. Its made with aim to show you reflection features.

class Person {

  const NAME_LENGTH_MAX = 50;

  protected $name;

  public function __construct($name){
    $this->name = $name;
  }

  /**
  * @return string
  */
  public function getName(){
    return $this->getName();
  }

  public static function generateName() {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $name = '';
    for ($i = 0; $i < self::NAME_LENGTH_MAX; $i++) {
        $name .= $characters[rand(0, $charactersLength - 1)];
    }
    return $name;
  }

}

What can we say about class Person ? It hasn't parent classes (it doesn't extend any class). It has one constant, one protected property, two functions and one constructor. - That's right. We able to get all this information in a program way. Consider the following script:

function echoInfoOnClass($object) {
    $reflectionClass = new \ReflectionClass($object);

    echo "Name: " . $reflectionClass->getName() . PHP_EOL; // echo class name (with namespace if any)
    echo "Short name: " . $reflectionClass->getShortName() . PHP_EOL; // echo class name without namespace
    // show all methods

    echo PHP_EOL;
    echo "Constants:" . PHP_EOL . PHP_EOL;
    foreach ($reflectionClass->getConstants() as $constantName => $constant) {
        echo $constantName . ' = ' . $constant . PHP_EOL;
    }

    echo PHP_EOL;
    echo "Properties:" . PHP_EOL . PHP_EOL;
    foreach ($reflectionClass->getProperties() as $property) {

        $propModifiers = \Reflection::getModifierNames($property->getModifiers()); // list of method modifiers (public,static, ..)

        foreach ($propModifiers as $modifier) { // echo all modifiers with space
            echo $modifier . " ";
        }

        $property->setAccessible(true); // this method of ReflectionProperty class make possible to access private or protected data on classes

        echo $property->getName() . ' = ' . json_encode($property->getValue($object)) . PHP_EOL;
    }

    echo PHP_EOL;
    echo "Methods:" . PHP_EOL . PHP_EOL;
    foreach ($reflectionClass->getMethods() as $method) {

        $methodModifiers = \Reflection::getModifierNames($method->getModifiers()); // list of method modifiers (public,static, ..)

        foreach ($methodModifiers as $modifier) { // echo all modifiers with space
            echo $modifier . " ";
        }

        echo $method->getName();

        $params = [];
        foreach ($method->getParameters() as $methodParam) {
            $currentParam = $methodParam->getName();
            if ($methodParam->isDefaultValueAvailable()) {
                $currentParam .= '=' . $methodParam->getDefaultValue();
                if ($methodParam->isDefaultValueConstant()) {
                    $currentParam .= '(' . $methodParam->getDefaultValueConstantName() . ')';
                }
            }
            $params[] = $currentParam;
        }

        // glue together pairs paramname - defaultvalue if any
        echo '(' . implode(',', $params) . ')';

        echo PHP_EOL;
    }
}

if we run the next code

echoInfoOnClass(new Person('Serhiy'));

we should get something like following response

Name: App\Controllers\Person
Short name: Person

Constants:

NAME_LENGTH_MAX = 50

Properties:

protected name = "Serhiy"

Methods:

public __construct(name)
public getName()
public static generateName(length=50(self::NAME_LENGTH_MAX))

As we can see, we gathered all info on class properties, constants and pethods, including visibility (public or protected or private), is it static or not and even property values. You can use my echoInfoOnClass in your programs if you want.

Its very helpfull to understand how we get such result by reading function code line by line.

Read next article How to invoke method on class with dynamicall generated name via reflection in course Reflection in PHP