php

PHP Private or Hidden Class


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?


Solution

  • 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.