Skip to content

Instantly share code, notes, and snippets.

@houssemz
Last active June 28, 2018 09:52
Show Gist options
  • Save houssemz/b6c8fb5e4b7ba0ee10e497f650150591 to your computer and use it in GitHub Desktop.
Save houssemz/b6c8fb5e4b7ba0ee10e497f650150591 to your computer and use it in GitHub Desktop.
Namespaces

Defining namespace :

Any valid PHP code can be contained within a namespace. But only the folowing types of code are affected by namespaces :

  • classes (including traits and abstracts)
  • functions
  • constantes

A file containg a namespace keyword must declare the namespace at the top of file and before any code. The only code allowed before namespace declaration is the declare statement for defining the encoding.

<html>
<?php
namespace MyProject; // fatal error - namespace must be the first statement in the script
?>

In addition, the same namespace may be defined in multipe files.

Defining multiple namespaces in the same file :

Multiple namespaces may also be declared in the same file. (two possible syntaxes)

<?php
 namespace MyProject {

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

namespace AnotherProject {

 const CONNECT_OK = 1;
 class Connection { /* ... */ }
 function connect() { /* ... */  }
}
?>
⛔ This syntax is recommanded. But it is strongly descouraged, as coding practice, to combine multiple namespaces into the same file.

No code may exist outside the namespace brackets except for an opening declare statement.

<?php
declare(encoding='UTF-8');
namespace MyProject {

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

namespace { // global code
  session_start();
  $a = MyProject\connect();
  echo MyProject\Connection::start();
}
?>

Using namespaces :

To understand how PHP knows which namespaced element (only classes, functions or constants) your code is requesting, a simple analogy can be made between PHP namespaces and filesystem :The are three way to access a file in a filesystem : - Relative file name like foo.txt => this resolves to current_directory/foo.txt - Relative path name kile subdirecotry/foo.txt => this resolves to currentdirectory/subdirecotry/foo.txt - Absolute path name like /main/foo.txt

Exp :

// file1.php
<?php
  namespace Foo\Bar\subnamespace;

  const FOO = 1;
  function foo() {}
  class Foo
  {
      static function staticmethod() {}
  }
 ?>
// file2.php
<?php
 namespace Foo\Bar;
 include 'file1.php';

 const FOO = 2;
 function foo() {}
 class Foo
 {
     static function staticmethod() {}
 }


 foo(); // resolve to currentnamespace/foo() = Foo\Bar\foo()
 Foo::staticmethod(); // revolve to Foo\Bar\Foo::staticmethod()
 echo FOO; // relove to Foo\Bar\FOO

 subnamespace\foo(); // reslove to Foo\Bar\subnamespace\foo()
 subnamespace\Foo::staticmethod(); // revolve to Foo\Bar\subnamespace\Foo::staticmethod()
 echo subnamespace\Foo;  // resolve to Foo\Bar\subnamespace\FOO

 \Foo\Bar\foo(); // resolves to function Foo\Bar\foo
 \Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
 echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO
?>

Tips :

  • 1/
<?php
  namespace foo;
  class MyClass {}
  function test(MyClass $typehintExample) {} // using type hint from the CURRENT namespace as type hint
?> 
  • 2/ Undefined Constants referenced using any backslash die with fatal error
<?php
  namespace bar;
  $a = FOO; // produces notice - undefined constants "FOO" assumed "FOO";
  $a = \FOO; // fatal error, undefined namespace constant FOO
  $a = Bar\FOO; // fatal error, undefined namespace constant bar\Bar\FOO
  $a = \Bar\FOO; // fatal error, undefined namespace constant Bar\FOO
?>

⛔ NB:

PHP does NOT allow nesting namespaces!

<?php
  namespace my\stuff {
      namespace nested {
          class foo {}
      }
  }
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment