Score code, devs, and debt fast.

Start free trial

How to Use PHP Namespaces, Part 3: Keywords and Autoloading

Craig Buckler
Craig Buckler
Published in
·Updated:

Share this article

SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools

7 Day Free Trial. Cancel Anytime.

PHP namespacesIn parts 1 and 2 of this series, we looked at PHP namespace basics, the use operator, and name resolution. In this final article we discuss some of the more advanced namespace options.

The __NAMESPACE__ Constant

__NAMESPACE__ is a PHP string that always returns the current namespace name. In the global space it will be an empty string.


<?php
namespace App\Lib1;
echo __NAMESPACE__; // outputs: App\Lib1
?>

The value has obvious benefits during debugging. It can also be used to dynamically generate a fully-qualified class name, e.g.


<?php
namespace App\Lib1;

class MyClass {
	public function WhoAmI() {
		return __METHOD__;
	}
}

$c = __NAMESPACE__ . '\\MyClass';
$m = new $c;
echo $m->WhoAmI(); // outputs: App\Lib1\MyClass::WhoAmI
?>

The namespace Keyword

The namespace keyword can be used to explicitly reference an item within the current namespace or a sub-namespace. It is the namespace equivalent of self within classes:


<?php
namespace App\Lib1;

class MyClass {
	public function WhoAmI() {
		return __METHOD__;
	}
}

$m = new namespace\MyClass;
echo $m->WhoAmI(); // outputs: App\Lib1\MyClass::WhoAmI
?>

Autoloading Namespaced Classes

One of the best time-saving features of PHP 5 is autoloading. In global (non-namespaced) PHP code, a standard autoload function could be written:


<?php
$obj1 = new MyClass1(); // classes/MyClass1.php is auto-loaded
$obj2 = new MyClass2(); // classes/MyClass2.php is auto-loaded

// autoload function
function __autoload($class_name) {
	require_once("classes/$class_name.php");
}
?>

In PHP 5.3, you can create an instance of a namespaced class. In that situation, the fully-qualified namespace and class name is passed to the __autoload function, e.g. the value of $class_name could be “AppLib1MyClass”. You could continue to place all your PHP class files in the same folder and strip the namespace from the string, however, that could result in file name clashes.

Alternatively, your class file hierarchy could be organized in the same way as your namespace structure. For example, a MyClass.php file could be created in the folder /classes/App/Lib1:

\classes\App\Lib1\MyClass.php:


<?php
namespace App\Lib1;

class MyClass {
	public function WhoAmI() {
		return __METHOD__;
	}
}
?>

A file in root folder could then use the following code:

myapp.php:


<?php
use App\Lib1\MyClass as MC;

$obj = new MC();
echo $obj->WhoAmI();

// autoload function
function __autoload($class) {

	// convert namespace to full file path
	$class = 'classes\' . str_replace('\\', '/', $class) . '.php';
	require_once($class);

}
?>

Explanation:

  1. The class AppLib1MyClass is aliased as MC.
  2. new MC() is translated to new AppLib1MyClass() during compilation.
  3. The string “AppLib1MyClass” is passed to the __autoload function. This replaces all namespace backslashes with file path forward slashes, and modifies the string so the file “classesAppLib1MyClass.php” is loaded.

I hope you found this series of PHP namespace articles useful. Will you be namespacing in your PHP code?

See also:

Frequently Asked Questions (FAQs) about PHP Namespaces, Keywords, and Autoloading

What is the purpose of using namespaces in PHP?

Namespaces in PHP serve as a way of encapsulating items. They are designed to solve two problems that authors of libraries and applications encounter: name collisions between code from different sources and the ability to alias or shorten long names. By using namespaces, developers can group related PHP classes, interfaces, functions, and constants together, avoiding any naming collisions.

How does the ‘use’ keyword function in PHP?

The ‘use’ keyword in PHP is used in conjunction with namespaces. It allows you to import classes, interfaces, functions, and constants from one namespace into another. This means you can access these elements without needing to specify their full namespace each time, making your code cleaner and easier to read.

Can I import multiple classes with the ‘use’ keyword?

Yes, you can import multiple classes with the ‘use’ keyword. This is done by listing the classes separated by commas within the curly braces after the namespace declaration. For example: use My\Full\Namespace{ClassA, ClassB, ClassC};

How does autoloading work in PHP?

Autoloading in PHP is a mechanism that automatically loads classes and interfaces when they are needed, without the need for explicit ‘include’ or ‘require’ statements. This can greatly simplify your code and make it easier to manage, especially in larger projects.

What are the benefits of using autoloading?

Autoloading provides several benefits. It simplifies your code by eliminating the need for manual ‘include’ or ‘require’ statements. It can also improve performance by only loading classes when they are actually used. Furthermore, it makes your code easier to manage and maintain, especially in larger projects.

How can I implement autoloading in my PHP project?

PHP provides several ways to implement autoloading. One common method is to use the ‘spl_autoload_register’ function. This function allows you to register multiple autoloaders, which can be useful in larger projects where you might have classes in different directories or namespaces.

What is the difference between ‘use’ and ‘require’ in PHP?

The ‘use’ keyword in PHP is used to import classes, interfaces, functions, and constants from one namespace into another. On the other hand, ‘require’ is used to include and evaluate a specific file. While ‘use’ deals with namespaces, ‘require’ deals with files.

Can I use namespaces in PHP without the ‘use’ keyword?

Yes, you can use namespaces in PHP without the ‘use’ keyword. However, you would need to refer to the full namespace each time you want to use a class, interface, function, or constant. The ‘use’ keyword simply makes it easier to refer to these elements by allowing you to import them into your current namespace.

Can I use the same namespace in multiple files?

Yes, you can use the same namespace across multiple files. This can be useful when you want to group related classes, interfaces, functions, and constants together, even if they are defined in different files.

How can I alias a class with the ‘use’ keyword?

You can alias a class with the ‘use’ keyword by following the class name with the ‘as’ keyword and the alias you want to use. For example: use My\Full\Namespace\ClassA as Alias; Now, you can refer to ClassA as Alias in your code.

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

Share this article

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.