Reading — step 1 of 6
Learn
In real PHP projects you don't have one giant file — you have a namespaced class per file, autoloaded on demand. This is what makes Composer (and the entire modern PHP ecosystem) work.
Declaring a namespace
At the top of a file (must be the first non-comment statement):
<?php
namespace App\Services;
class UserService {
public function find(int $id) { /* ... */ }
}
The class's fully-qualified name (FQN) is now \App\Services\UserService. Without a namespace declaration, classes go in the global namespace.
Using namespaced classes
Four ways to reference a class:
<?php
namespace App\Controllers;
use App\Services\UserService; // import → use short name
use App\Services\PostService as Posts; // alias
class HomeController {
public function index() {
$u = new UserService(); // imported short name
$p = new Posts(); // alias
$x = new \App\Other\Thing(); // FQN with leading backslash
$y = new \DateTimeImmutable(); // built-ins are global
}
}
Always use a leading \ for global classes like \Exception or \DateTime when you're inside a namespace — without it, PHP looks in your namespace first.
PSR-4 autoloading
The PSR-4 standard maps namespace prefixes to directory paths. With composer.json:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
The class App\Services\UserService lives at src/Services/UserService.php. Composer generates an autoloader that maps these — composer dump-autoload.
One class per file, filename matches class name (case-sensitive on Linux), directories match namespace segments. That's PSR-4.
use for functions and constants
Classes are imported by default. To import functions or constants explicitly:
use function App\Helpers\format;
use const App\MAX_SIZE;
Without use function, format(...) would look for it in the current namespace first, falling back to global.
Group use (PHP 7+)
use App\Services\{UserService, PostService, CommentService};
Cleaner than three separate use lines.
Common mistakes
- Forgetting the leading
\when calling built-ins inside a namespace —new DateTime()looks forApp\Services\DateTimefirst. - Mismatched filename/classname casing — works on macOS/Windows, breaks deploy on Linux.
- Putting
namespaceafter other code — must be the first statement in the file. - Trying to declare two namespaces in one file — legal but a code smell. Split them.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…