Named Constructor And Attribute
<?php
#[Attribute]
class Y {
public static function get(string $path): self {
return new self($path, 'GET');
}
// non public constructor
private function __construct(
public string $path,
public string $method
) {}
}
#[Y] // Actually, Y::get('/home')
class X {}
$reflectionClass = new ReflectionClass(X::class);
$attributes = $reflectionClass->getAttributes(Y::class);
foreach ($attributes as $attribute) {
$routeData = $attribute->getArguments();
$route = Y::get('mypath'); // Manually call the named constructor
}
PHP does not allow the use of named constructors, aka static factory methods, directly as attributes. However, you can work around this limitation by using reflection to access the attribute and then call the static method manually. It is just not the classic manual example, but, just don’t be too manual.
See Also
- Named Constructor With Attributes [Try me]
PHP Features
Last updated: 11 October 2026