PHP › Namespaces & Autoloading
How do you use the use keyword to import a class from a specific namespace, letting you reference it by its short name within a file?
BeginnerAnswer
The use keyword lets you import a specific class from another namespace at the top of a PHP file, allowing you to refer to that class using just its short name for the remainder of the file rather than needing to type out its full namespace path every single time it is referenced, significantly improving code readability when working with classes from multiple different namespaces.
use App\Models\User;
use App\Services\Mailer;
$user = new User();
$mailer = new Mailer();Real-world example A controller class imports both a User model and a Mailer service using the use keyword at the top of the file, allowing the rest of the file to reference both classes by their short, familiar names.