ReflectionClass
Information about a class: its methods, properties and attributes.
Syntax
new ReflectionClass(object|string $objectOrClass)Parameters
| Parameter | Type | Description |
|---|---|---|
| $objectOrClass | object|string | An object or a class name. |
Return value
ReflectionClassAn object with the `getShortName()`, `getMethods()`, `getProperties()`, `getAttributes()` and `newInstanceArgs()` methods.
Examples
What a class has:
<?php
class Product
{
public function __construct(public string $title, protected int $price) {}
public function price(): int
{
return $this->price;
}
}
$class = new ReflectionClass(Product::class);
echo $class->getShortName(), "\n";
echo implode(', ', array_map(fn ($p) => $p->getName(), $class->getProperties())), "\n";
echo implode(', ', array_map(fn ($m) => $m->getName(), $class->getMethods()));Output:
Product
title, price
__construct, priceNotes
Frameworks are built on reflection: that is how they find route attributes and learn which dependencies to pass to a constructor. Ordinary code rarely needs it.
See also
- get_class_methods — Returns the names of a class's methods.
- class_exists — Checks whether a class is defined.
- get_class — Returns the class name of an object.
In the tutorial
- Modern syntax — PHP 8 features — the ?-> operator, array destructuring, the spread operator, readonly classes, first-class callables and attributes.