Codectionary / Developer documentation / PHP

PHP reflection for class inspection

ReflectionClass inspects declared classes at runtime. It can examine interfaces, methods and constructor parameters when building tools or diagnosing a plugin contract.

Syntax

$reflection = new ReflectionClass($className);

Examples

PHP reflection for class inspection

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
interface Exporter { public function export(): string; }
class CsvExporter implements Exporter {
    public function export(): string { return 'csv'; }
}
$info = new ReflectionClass(CsvExporter::class);
echo $info->getName(), PHP_EOL;
echo $info->implementsInterface(Exporter::class) ? 'supported' : 'unsupported', PHP_EOL;
  1. Output: CsvExporter, then supported. Inspection does not require constructing CsvExporter.

Best practices

  • Prefer ordinary interfaces for application behavior. Reserve reflection for inspection or infrastructure and validate dynamically supplied class names.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading