Skip to content

Restrict instantiation of a class to specific allowed classes #19363

@jgrooen

Description

@jgrooen

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions