Limited Offer
60% OFF on all plans!

Namespaces & Autoloading in PHP

Organize your PHP code with namespaces, use the use keyword for imports, and set up PSR-4 autoloading with Composer.

Introduction to Namespaces

Namespaces prevent name collisions between classes, functions, and constants in large codebases or when combining third-party libraries. They act like folders for your code identifiers.

1. The Problem Without Namespaces

Name collisions in large projects.

2. Declaring a Namespace

namespace must be the first statement in the file.

3. Sub-Namespaces

Organize code in a hierarchy.

Using Namespaces — use & Aliases

The `use` keyword imports a fully qualified name so you can reference it by its short name within a file.

1. Importing with use

Import a class by its fully qualified name.

2. Aliasing with as

Resolve conflicts or shorten verbose names.

3. Importing Functions & Constants

use function and use const.

4. Accessing the Global Namespace

Prefix with \ to reference global classes inside a namespace.

Autoloading

Autoloading eliminates manual `require` statements. PHP calls a registered autoloader whenever an undefined class is used, letting it find and load the correct file on demand.

1. spl_autoload_register()

Register a custom autoloader function.

2. PSR-4 Autoloading Standard

The industry-standard convention for namespace-to-path mapping.

Composer Autoloading

Composer is PHP's dependency manager. It reads your `composer.json` and generates an optimised autoloader that handles both your code and all installed packages.

1. Configuring composer.json

Declare your PSR-4 mapping.

2. Requiring the Autoloader

One require at the entry point loads everything.

3. Optimizing for Production

Generate a classmap for faster autoloading.

4. Multiple Namespace Mappings

Map tests and other directories separately.