PHP
ReflectionClass
Learn a class's properties, methods and constants with ReflectionClass.
Class discovery with ReflectionClass
ReflectionClass maps a class. getMethods() returns methods, getProperties() properties and getConstructor() the constructor; each comes back as a reflection object.
If there is no constructor, getConstructor() returns null; do not call methods on it before checking. getShortName() gives the namespace-free name, isAbstract() and isFinal() describe the class.
The data is read-only: these calls describe the class, they do not change it.
getConstructor and getProperties
getConstructor() returns the constructor as a ReflectionMethod. If the class has no constructor you get null; in that case instantiation uses new $class without arguments.
getProperties() returns every property as a ReflectionProperty array. The filtered form getProperties(ReflectionProperty::IS_PRIVATE) lists only private ones.
Together these three calls reveal a class skeleton from the outside.
Exercise Print UserService method names
The UserService class is given. Build a ReflectionClass instance and print each method's name on a separate line using getMethods().
Show example solution
Build $rc = new ReflectionClass("UserService");. Print with foreach ($rc->getMethods() as $method) { echo $method->getName() . "\n"; }.
Example solution:
<?php
class UserService {
public function list(): array { return []; }
public function find(int $id): ?array { return null; }
}
$rc = new ReflectionClass("UserService");
foreach ($rc->getMethods() as $method) {
echo $method->getName() . "\n";
}
Test yourself
-
Loop with getMethods()
<?php
$rc = new ReflectionClass("UserService");
foreach ($rc->____() as $method) {
echo $method->getName() . "\n";
}
Show answer
<?php
$rc = new ReflectionClass("UserService");
foreach ($rc->getMethods() as $method) {
echo $method->getName() . "\n";
}
-
What does getConstructor() return?
- The constructor as a ReflectionMethod, or null
- All properties of the class as an array
- All methods of the class as an array
- The class's full name as a string
Show answer
The constructor as a ReflectionMethod, or null — Correct. The constructor is a ReflectionMethod; without one you get null.
-
Match ReflectionClass methods
- getMethods
- Returns the method list
- getProperties
- Returns the property list
- getConstructor
- Returns the constructor
- getShortName
- Returns the short class name
Next lesson: ReflectionMethod