Welcome to your journey into the PHP Reflection API! In this lesson, we'll delve into the fascinating world of introspection, where we can explore and manipulate PHP classes and functions. Let's get started! π
Reflection is a process that allows us to inspect and manipulate the structure of PHP classes, interfaces, functions, and methods at runtime. It's a powerful tool for creating dynamic applications and understanding the inner workings of PHP.
To work with the Reflection API, we'll use classes from the Reflection namespace. Here's how to create a ReflectionClass instance for a given class:
$reflectionClass = new ReflectionClass('ClassName');Let's see what we can do with a ReflectionClass instance:
$reflectionClass = new ReflectionClass('ClassName');
// Get class name
$className = $reflectionClass->getName();
// Get class methods
$methods = $reflectionClass->getMethods();
// Get class properties
$properties = $reflectionClass->getProperties();We can also access method and property details:
// Get method details
$method = $reflectionClass->getMethod('methodName');
$methodName = $method->getName();
$methodParameters = $method->getParameters();
// Get property details
$property = $reflectionClass->getProperty('propertyName');
$propertyName = $property->getName();
$propertyType = $property->getType();Let's create a simple class and explore it with the Reflection API:
class User {
private $name;
private $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getEmail() {
return $this->email;
}
public function setEmail($email) {
$this->email = $email;
}
}
$reflectionClass = new ReflectionClass('User');
// Get class name
echo $reflectionClass->getName() . "\n";
// Get class methods
foreach ($reflectionClass->getMethods() as $method) {
echo $method->getName() . "\n";
}
// Get class properties
foreach ($reflectionClass->getProperties() as $property) {
echo $property->getName() . "\n";
}Output:
User
__construct
getName
setName
getEmail
setEmail
name
email
We can further explore methods with the ReflectionMethod class:
$reflectionMethod = new ReflectionMethod('User', '__construct');
$reflectionMethod->invoke(new User('John', 'john@example.com'));$reflectionMethod = new ReflectionMethod('User', 'doesNotExist');
if ($reflectionMethod->exists()) {
echo "Method exists\n";
} else {
echo "Method does not exist\n";
}What is the Reflection API used for in PHP?
How can we instantiate a `ReflectionClass` for a given class?
How can we access the properties of a class using Reflection?
Continue your PHP journey with us at CodeYourCraft! Stay tuned for more exciting lessons and practical examples. Happy coding! π‘ π―