Importing with use
Learn to import a class from another namespace with use.
Importing with use
Writing the fully qualified name every time is tiring. With use App\Models\User; you import the class; afterwards you only need to write User.
The use declaration goes after the namespace declaration and before any class definition. To import several classes, write a separate use line for each.
Fully qualified vs short name
Without use you must write the fully qualified name: new \App\Models\User(). The leading \ means start from the root namespace.
After use App\Models\User; you can write new User(). Both forms call the same class; use only improves readability.
Exercise Import and use a class with use
Inside the App\Service namespace, import App\Models\User with use. Create new User("Alex") and print the $user->name property. The demo uses braced syntax to define two namespaces in one file.
Show example solution
Write use App\Models\User;. Create with $user = new User("Alex"); and print with echo $user->name . "\n";.
Example solution:
<?php
namespace App\Models {
class User {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
}
namespace App\Service {
use App\Models\User;
$user = new User("Alex");
echo $user->name . "\n";
}
Test yourself
-
Complete the use statement
<?php namespace App\Service; ____ App\Models\User; $cfg = ["role" => "admin"]; $user = new User();Show answer
<?php namespace App\Service; use App\Models\User; $cfg = ["role" => "admin"]; $user = new User(); -
What does use App\Models\User; do?
- It lets you use the short name User in this file only
- It permanently renames the User class
- It deletes the App\Models namespace
- It creates a new User class
Show answer
It lets you use the short name User in this file only — Correct. With use the User class is referenced by its short name in this file.
-
Match the use concepts
- use ...;
- Imports a class
- new User()
- Instantiates with short name
- \App\Models\User
- Fully qualified path
- use
- Import keyword