330 of 410 menu

The namespace Command

Namespaces in PHP allow isolating classes, interfaces, functions, and constants. They are especially useful when working with large projects or using third-party libraries. A namespace is defined with the keyword namespace at the beginning of a file.

Syntax

namespace MyProject;

Example

Let's create a simple namespace and a class inside it:

<?php namespace MyProject; class MyClass { public function hello() { return 'Hello from MyClass'; } } ?>

Example

Accessing a class from another namespace:

<?php require_once 'MyClass.php'; $obj = new \MyProject\MyClass(); echo $obj->hello(); ?>

Code execution result:

'Hello from MyClass'

Example

Using aliases for namespaces:

<?php use MyProject\MyClass as MC; $obj = new MC(); echo $obj->hello(); ?>

See Also

  • the class command,
    which allows creating classes
byenru