Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 147 ยท Advanced PHP

Reflection

Use PHP's Reflection API to inspect classes, methods, properties and types at run time, call private code in tests, and build a tiny autowiring DI container.

Reflection is code that looks at code. With PHP's Reflection API you can ask a class, at run time, which methods it has, what parameters each one takes, which types they declare, what attributes they carry and what their DocBlock says. You can also create objects and call methods through those reflection objects.

Application code rarely needs this directly, but almost every framework is built on it. A dependency injection container reads constructor parameter types to build services automatically. A router reads attributes to find routes. An ORM maps properties to columns, a serializer turns objects into JSON, and testing tools generate mocks, all by reflecting on your classes. Understanding Reflection lets you see how those tools work and write small versions of them yourself. This lesson ends by building a tiny autowiring container in about 40 lines.

Reflecting on a class

Everything starts with a reflection object. new ReflectionClass(SomeClass::class) (or an object instance) gives you a ReflectionClass, and from there you can reach every part of the class:

PHP Inspecting a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A few things to notice. getName() returns the fully qualified name including the namespace; getShortName() drops it. getDocComment() returns the raw /** ... */ text, which is how older tools read annotations (or false if there's none). The promoted constructor parameter $number shows up as a normal property.

Useful ReflectionClass methods at a glance:

Question Method
Is it abstract / final / an interface / an enum? isAbstract(), isFinal(), isInterface(), isEnum()
Can I call new on it? isInstantiable()
Does it implement or extend X? implementsInterface(), isSubclassOf()
What does it contain? getMethods(), getProperties(), getConstants(), getTraitNames()
Where is it defined? getFileName(), getStartLine()
Make an instance newInstance(...), newInstanceArgs([...]), newInstanceWithoutConstructor()

Use ReflectionObject when you start from an object; it's a subclass of ReflectionClass that also sees dynamic properties.

Methods, functions and parameters

ReflectionMethod (and ReflectionFunction for plain functions and closures) describe signatures in detail: the parameters with their types, defaults and modifiers, and the return type.

PHP Reading a function signature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The same code works for your methods, built-in functions like str_pad() and closures. Since PHP 8.4 a closure's name says where it was defined, like {closure:main.php:37}, which also makes stack traces easier to read. Converting a type or reflection object to a string (as sprintf('%s', ...) does here) gives a readable form such as ?string or int|float.

Inspecting types

Types are objects too. getType() returns a subclass of ReflectionType:

  • ReflectionNamedType for a single type such as int, ?string or Invoice. getName() gives the name without the ?, allowsNull() tells you about nullability, and isBuiltin() separates int/string/array from class names.
  • ReflectionUnionType for A|B, and ReflectionIntersectionType for A&B. Their getTypes() returns the members.

Notice that int|string comes back as string|int: PHP stores union types in its own order, so never compare type strings literally; compare the member names instead. You'll use exactly these checks in the container below: a parameter typed with a class name can be built automatically; a builtin type like string cannot.

PHP Named, union and intersection types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Reading and calling private members

Reflection can read private properties and call private methods. Since PHP 8.1 this works directly; older code calls setAccessible(true) first, which is now a no-op you can delete.

PHP Accessing private state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This is a tool for frameworks (hydrating objects from database rows), serializers and the occasional test of legacy code. In your own application code it's a smell: if you need to reach into private state, the class is probably missing a public method. And tests that poke private members break whenever the internals change, even if the behavior didn't. Prefer testing through the public API, as Testing PHP Code recommends.

Creating objects dynamically

newInstanceArgs() calls the constructor with an array of arguments. String keys are treated as named arguments (PHP 8.0+), which lets you build objects from configuration arrays:

PHP
<?php
$class = new ReflectionClass(DateTimeImmutable::class);
$date = $class->newInstanceArgs(['datetime' => '2026-01-15', 'timezone' => new DateTimeZone('UTC')]);
echo $date->format('Y-m-d');   // 2026-01-15

newInstanceWithoutConstructor() skips the constructor entirely. ORMs use it to create an entity and then fill its properties from a database row, since the constructor might require arguments the row doesn't map to directly.

PHP 8.4 added lazy objects to ReflectionClass: newLazyGhost() and newLazyProxy() create an object whose initialization runs only when you first touch it. Doctrine and Symfony use this for lazy-loaded entities and services, replacing a lot of generated proxy code:

PHP A lazy ghost object (PHP 8.4)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The constructor's message appears only when $report->rows is first read, not when the object is created. If the code had never used the report, the expensive work would never have happened.

How frameworks use Reflection

Here's the big picture before you build one:

  • Dependency injection containers (Laravel's container, Symfony DI, PHP-DI) read constructor parameter types and create dependencies recursively. This is called autowiring.
  • Routers and event systems read attributes on methods (see Attributes).
  • ORMs and serializers read property types and attributes to map objects to tables or JSON.
  • Test frameworks find test methods and data providers, and mocking libraries generate subclasses that match a class's signatures.
  • Static analysers like PHPStan mostly parse source code instead, but use Reflection for built-in and compiled classes.

Reflection is fast enough for all of this, but it isn't free. Frameworks typically reflect once and cache the results (compiled containers, route caches), so production requests don't repeat the work. See Performance and OPcache.

Building a tiny autowiring container

A container's job: when you ask for a class, build it, along with everything its constructor needs. With Reflection the logic is short:

  1. If there's a manually registered factory or binding for the requested ID, use it.
  2. Otherwise reflect on the class. If it has no constructor, just new it.
  3. For each constructor parameter: if its type is a class or interface, resolve it recursively; if it has a default value, use that; otherwise fail with a clear message.
  4. Remember the instance, so each service is created once (a "shared" service).
PHP An autowiring DI container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You asked for one class, SignupService, and the container built the whole tree: UserRepository (with the bound PDO factory), Logger (with the Clock interface mapped to FixedClock, and the default 'app' for the string parameter). Classes never call new on their dependencies; they just declare them. That's dependency injection, and the container is merely the convenience that wires it up.

Real containers add more on top: scoped and non-shared services, contextual bindings, resolving union types, #[Autowire]-style attributes for scalar config values, and compiling the resolved graph to plain PHP so production skips Reflection completely. Design Patterns in PHP discusses containers alongside the other patterns.

A container you reach into from everywhere (Container::getInstance()->get(...) inside business code) is the service locator anti-pattern: it hides dependencies again. Resolve the top-level object once, at the edge of your application (the front controller or command), and let constructor injection do the rest.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For function f(?string $name), what do getType()->getName() and getType()->allowsNull() return?

    ReflectionNamedType::getName() returns the type name without the question mark; allowsNull() reports the nullability separately. Casting the type to a string would give ?string.
  2. 2. How does an autowiring container decide what to pass for a constructor parameter typed Logger $logger?

    The container reflects on the constructor, finds a class type (isBuiltin() is false), and builds or reuses that class the same way.
  3. 3. What does ReflectionClass::newInstanceWithoutConstructor() do?

    It allocates the object with default property values but skips __construct(). ORMs use it to hydrate entities from database rows.
  4. 4. Since PHP 8.1, what is needed before ReflectionProperty::getValue() can read a private property?

    Since PHP 8.1 reflection can access private and protected members without setAccessible(), which became a no-op.
  5. 5. Why do frameworks cache what they learn through Reflection?

    Reflection is reasonably fast, but rebuilding route tables or container graphs on every request adds up. Compiling them once per deploy avoids that work.

Summary

  • Reflection lets code inspect code at run time: ReflectionClass/ReflectionObject, ReflectionMethod, ReflectionFunction, ReflectionProperty, ReflectionParameter and the type classes.
  • Types come back as ReflectionNamedType (with getName(), allowsNull(), isBuiltin()), ReflectionUnionType or ReflectionIntersectionType.
  • Reflection can read and write private members (no setAccessible() needed since 8.1). Use that in frameworks and tools, not in application logic.
  • newInstanceArgs() (with named arguments), newInstanceWithoutConstructor() and PHP 8.4's lazy objects (newLazyGhost(), newLazyProxy()) create objects dynamically.
  • DI containers, routers, ORMs, serializers and test tools are built on Reflection. Autowiring resolves class-typed constructor parameters recursively.
  • Reflect once and cache the result; resolve your object graph at the application's edge instead of using a service locator.

Next: Fibers and Asynchronous PHP