Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a namespace and how is it implemented in PHP?

Tags:

namespaces

php

I've heard the latest PHP has support for namespaces. I know variables defined in the global scope have no namespace, so how does one make a variable in a different namespace?

Is it just a way of categorising variables/functions?

like image 286
alex Avatar asked Feb 27 '09 05:02

alex


2 Answers

Namespaces are a programming language mechanism for organizing variables, functions and classes. PHP 5.3 adds support for namespaces, which I'll demonstrate in the following example:

Say you would like to combine two projects which use the same class name User, but have different implementations of each:

// Code for Project One (proj1.php)
<?php
  class User {
    protected $userId;
    public function getUserId() {
      return $this->userId;
    }
  }
  $user = new User;
  echo $user->getUserId();
?>

// Code for Project Two (proj2.php)
<?php
  class User {
    public $user_id;
  }
  $user = new User;
  echo $user->user_id;
?>

<?php
  // Combine the two projects
  require 'proj1.php';
  require 'proj2.php'; // Naming collision!
  $myUser = new User; // Which class to use?
?>

For versions of PHP less than 5.3, you would have to go through the trouble of changing the class name for all instances of the class User used by one of the projects to prevent a naming collision:

<?php
  class ProjectOne_User {
    // ...
  }
  $user = new ProjectOne_User; // Code in Project One has to be changed too
?>

For versions of PHP greater than or equal to 5.3, you can use namespaces when creating a project, by adding a namespace declaration:

<?php
  // Code for Project One (proj1.php)
  namespace ProjectOne;
  class User {
    // ...
  }
  $user = new User;
?>

<?php
  // Combine the two projects
  require 'proj1.php';

  use ProjectOne as One; // Declare namespace to use

  require 'proj2.php' // No collision!

  $user = new \One\User; // State which version of User class to use (using fully qualified namespace)

  echo $user->user_id; // Use ProjectOne implementation
?>

For more information:

  • PHP.net Namespaces
  • PHP Namespaces
like image 64
Jake McGraw Avatar answered Oct 12 '22 04:10

Jake McGraw


A namespace allows you to organize code and gives you a way to encapsulate your items.

You can visualize namespaces as a file system uses directories to group related files.

Basically namespaces provide you a way in which to group related classes, functions and constants.

They also help to avoid name collisions between your PHP classes/functions/constants, and improve the code readability, avoiding extra-long class names.

Example namespace declaration:

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

?>
like image 41
Christian C. Salvadó Avatar answered Oct 12 '22 02:10

Christian C. Salvadó