[php-src] Issue #19363: Restrict instantiation of a class to specific allowed classes

From: Date: Mon, 04 Aug 2025 09:48:44 +0000
Subject: [php-src] Issue #19363: Restrict instantiation of a class to specific allowed classes
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-250556@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/19363 Author: jgrooen ### 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: ```php #[AllowInstantiationOnlyBy(PostRepository::class)] final class MysqlPostRepository {} ``` --- #### **Benefit:** Enforces encapsulation Prevents misuse Encourages better architecture --- #### **Compatibility:** Fully opt-in, no breaking changes.

« previous php.bugs (#250556) next »