How to create and use namespaces

How to create a namespace in a file

Using the statement syntax

      <?php 
      namespace cart; // Functions in cart namespace 
      ?>
      

Using the brace syntax

      <?php 
      namespace murach\cart {
        // Functions in murach\cart namespace 
      }
      ?>
      

How to create nested namespaces

      <?php 
      namespace cart {
        // Functions in cart namespace 
      }
      ?>      
      

How to use the functions that are defined in a namespace

Create a file that contains a namespace with one function

      <?php 
      namespace murach\errors {
        function log($error) { 
          echo(<p> class='error'>$error</p>
        }
      }
      ?>
      

Call a function that is stored in the namespace

  
      // load the file that stores the namespace 
      require_once 'errors.php';
      

      // call the log function murach\errors\log('Invalid value');
      // create an alias and use it to call the log function 
      use murach\errors as e; // Use 'e' instead of 'murach\errors'
      e\log('Invalid value');
      

Back