4

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?

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.