When building tools that inspect PHP code, ReflectionClass::newInstance() helps answer a focused question: creates a new instance of the reflected class while invoking its constructor.
Reflection is useful in framework tooling, dependency injection, testing, code inspection and debugging.
What Is ReflectionClass::newInstance()?
Creates a new instance of the reflected class while invoking its constructor.
Its method signature is:
public function newInstance(mixed ...$args): object
Parameters:
$args— Positional values passed to the target constructor or callable Accepts additional arguments.
Return value: object
Example 1: Inspect a PHP class declaration
Start with a self-contained PHP declaration and inspect the method result.
<?php
declare(strict_types=1);
#[Attribute(Attribute::TARGET_CLASS_CONSTANT | Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER | Attribute::TARGET_FUNCTION)]
class GuideTag { public function __construct(public string $label) {} }
trait HasIdentifier { public function identifier(): int { return 20; } }
interface NamedEntity { public function name(): string; }
class BaseEntity { public const string BASE = 'entity'; protected int $revision = 1; public static int $total = 4; }
class Shipment extends BaseEntity implements NamedEntity, IteratorAggregate {
use HasIdentifier;
#[GuideTag('category')]
final public const string TYPE = 'parcel';
private const int SECRET = 5;
public string $title = 'Box';
public function __construct(public int $number = 10) {}
public function name(): string { return $this->title; }
public function getIterator(): Traversable { yield 'item' => $this->title; }
public function deliver(string $destination = 'office'): string { return 'Sent to ' . $destination; }
}
readonly class ImmutableShipment { public function __construct(public string $title = 'Box') {} }
$classReflection = new ReflectionClass(Shipment::class);
$result = $classReflection->newInstance(18);
echo get_class($result);
Output:
Shipment
Explanation: Creates a new instance of the reflected class while invoking its constructor.
Example 2: Compare a different class target
Next, change the reflected declaration or parameter to observe a related situation.
<?php
declare(strict_types=1);
#[Attribute(Attribute::TARGET_CLASS_CONSTANT | Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER | Attribute::TARGET_FUNCTION)]
class GuideTag { public function __construct(public string $label) {} }
trait HasIdentifier { public function identifier(): int { return 20; } }
interface NamedEntity { public function name(): string; }
class BaseEntity { public const string BASE = 'entity'; protected int $revision = 1; public static int $total = 4; }
class Shipment extends BaseEntity implements NamedEntity, IteratorAggregate {
use HasIdentifier;
#[GuideTag('category')]
final public const string TYPE = 'parcel';
private const int SECRET = 5;
public string $title = 'Box';
public function __construct(public int $number = 10) {}
public function name(): string { return $this->title; }
public function getIterator(): Traversable { yield 'item' => $this->title; }
public function deliver(string $destination = 'office'): string { return 'Sent to ' . $destination; }
}
readonly class ImmutableShipment { public function __construct(public string $title = 'Box') {} }
$classReflection = new ReflectionClass(Shipment::class);
$result = $classReflection->newInstance(24);
echo get_class($result);
// Check the returned value type before using the result.
echo "\nResult type: " . get_debug_type($result);
Output:
Shipment
Result type: Shipment
Explanation: Required constructor arguments must be supplied; abstract classes cannot be instantiated.
Practical Example: Apply reflection to a real object model
This final case shows how the same API can be used when inspecting application definitions.
<?php
declare(strict_types=1);
#[Attribute(Attribute::TARGET_CLASS_CONSTANT | Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER | Attribute::TARGET_FUNCTION)]
class GuideTag { public function __construct(public string $label) {} }
trait HasIdentifier { public function identifier(): int { return 20; } }
interface NamedEntity { public function name(): string; }
class BaseEntity { public const string BASE = 'entity'; protected int $revision = 1; public static int $total = 4; }
class Shipment extends BaseEntity implements NamedEntity, IteratorAggregate {
use HasIdentifier;
#[GuideTag('category')]
final public const string TYPE = 'parcel';
private const int SECRET = 5;
public string $title = 'Box';
public function __construct(public int $number = 10) {}
public function name(): string { return $this->title; }
public function getIterator(): Traversable { yield 'item' => $this->title; }
public function deliver(string $destination = 'office'): string { return 'Sent to ' . $destination; }
}
readonly class ImmutableShipment { public function __construct(public string $title = 'Box') {} }
$classReflection = new ReflectionClass(Shipment::class);
$result = $classReflection->newInstance(35);
echo get_class($result);
// Use the reflection result in a simple decision.
if (is_bool($result)) {
echo "\nStatus: " . ($result ? "yes" : "no");
} elseif (is_array($result)) {
echo "\nEntries: " . count($result);
} elseif ($result === null) {
echo "\nNo value returned";
} else {
echo "\nReflection result available";
}
Output:
Shipment
Reflection result available
Explanation: newInstanceWithoutConstructor skips normal constructor execution.
Important Behavior and Edge Cases
- Required constructor arguments must be supplied; abstract classes cannot be instantiated.
- newInstanceWithoutConstructor skips normal constructor execution.
- Reflection describes declarations and runtime state; requesting metadata does not automatically validate or sanitize application input.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
ReflectionClass::newInstance() | Creates a new instance of the reflected class while invoking its constructor. |
Related API | newInstanceWithoutConstructor skips normal constructor execution. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this condition: Required constructor arguments must be supplied; abstract classes cannot be instantiated. | Handle the specific limitation: Required constructor arguments must be supplied; abstract classes cannot be instantiated. |
| Confusing this method with Related API | newInstanceWithoutConstructor skips normal constructor execution. |
Key Takeaways
- Creates a new instance of the reflected class while invoking its constructor.
- Required constructor arguments must be supplied; abstract classes cannot be instantiated.
- newInstanceWithoutConstructor skips normal constructor execution.
Use ReflectionClass::newInstance() when you need the precise metadata or behavior demonstrated above. Keep the target declaration and relevant PHP version in mind when adapting the examples.