Skip to content

Chapter 22 of 38

Namespaces and Autoloading

Organize names, aliases, Composer autoloading, and PSR-4 project layout.

34 minutes 10 quick checksBy Subha Prasad
Lesson 22 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Namespaces prevent collisions and make package ownership explicit. use imports or aliases classes, functions, and constants; it does not load files by itself.

Practical example

<?php
namespace App\Learning;
use DateTimeImmutable as DateTime;
final class Lesson { public function createdAt(): DateTime { return new DateTime(); } }

Composer generates autoloaders, commonly using PSR-4 mappings from namespace prefixes to directories. Avoid manual require chains, global namespace pollution, ambiguous aliases, and source trees that do not match their declared autoload rules.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes namespace?
Which PHP term matches this description: A declaration grouping names and avoiding collisions.
Which statement best describes use import?
Which PHP term matches this description: An alias/import for a class, function, or constant name.
Which statement best describes fully qualified name?
Which PHP term matches this description: A name beginning from the global namespace.
Which statement best describes namespace-relative name?
Which PHP term matches this description: A name explicitly resolved from the current namespace.
Which statement best describes PSR-4?
Which PHP term matches this description: A convention mapping namespace prefixes to filesystem directories.

0 of 10 checks passed

Your progress is saved on this device.