Beginner LevelPHP 8+
How do PHP namespaces prevent class naming collisions and how does the use keyword alias imports?
❓ Interview Prompt: Explain PHP namespaces, FQCN (Fully Qualified Class Names), the use statement, and class name aliasing (as).
Namespaces organize code into logical directory-like structures to prevent class naming collisions between different libraries.
Core Namespace Rules:
1
Declaration: Declared at the very top of a file using 'namespace AppServices;'.
2
Fully Qualified Class Name (FQCN): Absolute path to a class, starting with a backslash ('AppServicesPaymentService').
3
The 'use' Statement: Imports a class into the current file scope so you can reference it by short name.
4
Aliasing ('as'): Rename imported classes to avoid collisions when two packages share a class name ('use StripeCharge as StripeCharge;').
Code Implementation Example
php
<?php
namespace AppControllers;
// Import external classes into current namespace scope
use AppServicesPaymentService;
use StripeCharge as StripeCharge; // Alias to prevent collisions!
class OrderController {
public function checkout(): void {
$payment = new PaymentService();
$stripe = new StripeCharge();
}
}💡Using PHP namespaces, use statements, and class aliasing.
🎯 Interview Key Takeaway
Namespaces isolate code libraries to prevent naming collisions. Use the use keyword with aliases (as) to manage class imports cleanly.
#Namespaces#use Keyword#Aliasing#Beginner
Back to all PHP 8+ Questions→