Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

ReflectionClass

Information about a class: its methods, properties and attributes.

Syntax

new ReflectionClass(object|string $objectOrClass)

Parameters

ParameterTypeDescription
$objectOrClassobject|stringAn 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, price

Notes

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

In the tutorial

  • Modern syntax — PHP 8 features — the ?-> operator, array destructuring, the spread operator, readonly classes, first-class callables and attributes.

Thanks for reading!

Donate to the site — we work hard for you.