Skip to content
Featherwebs

Namespace

  • A way of encapsulating items.
  • Like a virtual folder or directory defined with namespace keyword at the top of a file followed by name of the namespace.
  • Namespace can be used to organize code into logical groups and prevent name collisions.
  • Allows to define two classes with the same name in different namespaces.

Standard Way of Defining a Class.

class ClassName {
    // code
}

$object = new ClassName();

Defining a Class in a Namespace

namespace MyNamespace;

class ClassName {
    // code
}

$object = new MyNamespace\ClassName();

Difining a Class in a Namespace (Other files)

use MyNamespace\ClassName;

$object = new ClassName();