Feature Request
Add a language-level way to restrict instantiation of a class to only specific classes.
Use Case
For example, I want MysqlPostRepository and RedisPostRepository to be instantiated only inside PostRepository, and not from any other class.
Currently, there's no clean or built-in way to enforce this behavior in PHP.
Current Workaround
Using private or protected constructors with debug_backtrace() checks in static factory methods —
but this approach is runtime-only, fragile, and not enforced by the language.
Proposal
Introduce a syntax or attribute like:
#[AllowInstantiationOnlyBy(PostRepository::class)]
final class MysqlPostRepository {}
Benefit
Enforces encapsulation
Prevents misuse
Encourages better architecture
Compatibility
Fully opt-in, no breaking changes.
Feature Request
Add a language-level way to restrict instantiation of a class to only specific classes.
Use Case
For example, I want
MysqlPostRepositoryandRedisPostRepositoryto be instantiated only insidePostRepository, and not from any other class.Currently, there's no clean or built-in way to enforce this behavior in PHP.
Current Workaround
Using
privateorprotectedconstructors withdebug_backtrace()checks in static factory methods —but this approach is runtime-only, fragile, and not enforced by the language.
Proposal
Introduce a syntax or attribute like:
Benefit
Enforces encapsulation
Prevents misuse
Encourages better architecture
Compatibility
Fully opt-in, no breaking changes.