-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Open
Description
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.
MR-Sharifi