Aliases
Learn to alias long class names with use ... as.
Aliases with use ... as
To shorten long class names you can write use App\Services\AccountService as AccountSvc;. Afterwards new AccountSvc() is enough.
The as keyword gives the class a different short name. The real class name does not change; only its use in this file is shortened.
When do you need an alias?
If the same file needs same-named classes from two namespaces, an alias is required. For example, when both App\Models\User and App\Auth\User are needed, import one as UserModel and the other as UserAuth.
Otherwise PHP raises a collision error and the file does not run.
Exercise Use a class with an alias
Inside the App\Controller namespace, import App\Services\AccountService with the alias AccountSvc. Create new AccountSvc() and print the value returned by $svc->owner(). The demo uses braced syntax to define two namespaces in one file.
Show example solution
Write use App\Services\AccountService as AccountSvc;. Create with $svc = new AccountSvc(); and print with echo $svc->owner() . "\n";.
Example solution:
<?php
namespace App\Services {
class AccountService {
public function owner(): string {
return "Alex";
}
}
}
namespace App\Controller {
use App\Services\AccountService as AccountSvc;
$svc = new AccountSvc();
echo $svc->owner() . "\n";
}
Test yourself
-
What does use App\Services\User as UserSvc; do?
- It deletes the User class
- It creates a new UserSvc class
- It imports User under the name UserSvc
- It produces a copy of the User class
Show answer
It imports User under the name UserSvc — Correct. With as, the User class is imported under the name UserSvc.
-
Complete the alias statement
<?php namespace App\Controller; ____ App\Services\AccountService as AccountSvc; $cfg = ["alias" => "AccountSvc"]; $svc = new AccountSvc();Show answer
<?php namespace App\Controller; use App\Services\AccountService as AccountSvc; $cfg = ["alias" => "AccountSvc"]; $svc = new AccountSvc(); -
Match the alias concepts
- use ... as
- Gives an alias
- App\Auth\User as UserAuth
- Names the second User
- new UserAuth()
- Instantiates with alias
- as
- Alias keyword