I am trying to only allow access to certain php classes within certain namespaces. Is there a way or work-around to make php classes only visible or accessible within a namespace kind of like C#’s internal scope?
2 Answers
In PHP, you can't have nested classes.
You can use namespaces and private members.
// Root namespace namespace MyParentClass { use MyParentClass\PrivateClass\PrivateNode; class Node { private $privateClass; public function getPrivateClass() { if (!isset($this->privateClass)) { $this->privateClass = new PrivateNode(); } return $this->privateClass; } } } // Pseudo scope namespace MyParentClass\PrivateClass { class PrivateNode { private $name = 'PrivateNode'; public function getName() { return $this->name; } } } // Test script namespace { $node = new MyParentClass\Node(); echo $node->getPrivateClass()->getName(); } ?> Hope this helps.
Note: Daniel put a link to anonymous classes which can be another interesting way.
Comments
What about this?
class EntryPoint { public object $privateCollaborator; public function __construct() { $this->privateCollaborator = self::getPrivateCollaborator(); } private static function getPrivateCollaborator() { return new class { }; } } $entryPoint = new EntryPoint(); I sometimes use it so as not to dirty the LSP-Intelephense autocomplete in Sublime Text. If I remove the object type to the property at the entrance point, LSP-Intelephense will recognize the reference of the object, being able to self-fulfill the members of that collaborator