Skip to content

Chapter 3 of 7

Namespaces and Dependency Management

As PHP projects grow, name collisions become inevitable: two libraries may both define a class called User or Logger. Namespaces solve this by acting as virtual directories for your code. Declaring a namespace at the top of a file, such as namespace App\Models;, groups related classes together and prevents unintended clashes with similarly named code elsewhere. Namespaces follow the file structure loosely and provide a hierarchical naming scheme that mirrors modern project organization.

To refer to a namespaced class from another file, you use the use statement, optionally aliasing it with the as keyword to make code more readable. This works much like importing a symbol into the current namespace so that you can refer to it by its short name instead of its fully qualified path. Aliasing is particularly helpful when dealing with long names or when importing two classes that would otherwise share a short name within the same file.

Outside the standard library, PHP relies on Composer as its de facto dependency manager. You declare your project's dependencies in a composer.json file, and running composer require vendor/package both installs the package and records it under the require section. Composer also generates an autoloader in vendor/autoload.php that you include once at the entry point of your application. This autoloader supports PSR-4, PSR-0, classmap, and files-based autoloading, so classes are loaded on demand without manual require statements. A composer.lock file locks the exact versions installed, ensuring reproducible builds across environments and machines.

All chapters
  1. 1Object-Oriented Foundations
  2. 2Inheritance, Interfaces, and Traits
  3. 3Namespaces and Dependency Management
  4. 4The PHP Type System
  5. 5Working with Arrays and Strings
  6. 6Databases, Sessions, and Error Handling
  7. 7Closures, Generators, and Magic Methods

Drill it

Reading is not remembering. These come from the Php Programming deck:

Q

What is a class in PHP OOP?

A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects will have.class User { public string $na...

Q

What is the difference between public, protected, and private visibility in PHP?

public – accessible from anywhere.protected – accessible within the class and its subclasses.private – accessible only within the defining class.These are known...

Q

How do you create an object from a class in PHP?

Use the new keyword:$user = new User();This calls the class constructor (__construct) if one is defined.

Q

What is the purpose of the __construct() magic method?

__construct() is the constructor that runs automatically when an object is created with new.public function __construct(public string $name) {}It initializes ob...