Defining namespaces
Learn to package code with the namespace keyword.
What is namespace for?
In some projects same-named classes clash: two libraries may both define User. namespace solves this; it sorts classes into packages. When you write namespace App;, the User class actually carries the name App\User.
The declaration goes right after the PHP opening tag, as the first statement in the file. Every class, function and constant below joins this namespace. Use \ to separate levels: App\Models\User.
How do you write a namespace declaration?
When you write namespace App\Models; in a file, PHP places every class in that file under the App\Models package. Before the declaration only the PHP opening tag and a declare statement may appear; no other code.
The __NAMESPACE__ constant returns the current namespace name as a string. This is useful when debugging or building class names dynamically.
Exercise Define a namespace and a class
Define namespace App\Utils;. Add a Helper class with public static function greet($name) that prints the name with a "Hello, " prefix. Then call Helper::greet("Alex") and print __NAMESPACE__.
Show example solution
:greet("Alex"); and echo __NAMESPACE__ . "\n".
Example solution:
<?php
namespace App\Utils;
class Helper {
public static function greet($name) {
echo "Hello, " . $name . "!\n";
}
}
Helper::greet("Alex");
echo __NAMESPACE__ . "\n";
Test yourself
-
What does namespace do?
- It runs code faster
- It prevents same-name class collisions
- It manages database connections
- It provides automatic error handling
Show answer
It prevents same-name class collisions — Correct. namespace sorts same-named classes into different packages.
-
Complete the namespace declaration
<?php ____ App\Services\UserService; class UserService { public array $info = ["name" => "default"]; }Show answer
<?php namespace App\Services\UserService; class UserService { public array $info = ["name" => "default"]; } -
Match the namespace concepts
- namespace
- Packages code
- __NAMESPACE__
- Gives current name
- \
- Level separator
- ;
- Ends the declaration