PHP
Using traits with use
Learn to include a trait's methods in a class with use.
Including a trait in a class with use
You've defined a trait; now let's use it in a class. Inside the class body you write use TraitName;. This line injects the trait's methods into the class; they work as if you had written them by hand.
Example:
class User {
use Greeter;
}
$u = new User();
echo $u->hello(); // Hello
This use appears inside a class body with a trait name.
Method injection: a trait method works in the class
When you write use Greeter;, the hello() method of the Greeter trait becomes part of the User class. This is called method injection. Calling $u->hello() runs the trait's method.
Traits can also hold properties; these are injected too. This way you keep shared state and behavior in one place and spread it across many classes.
Key point: a trait cannot be instantiated with new; only a class uses it via use.
Exercise Use the Logger trait in the Service class
Define a Logger trait: its public function log(string $msg): string method does return "[LOG] " . $msg;. Then a Service class uses the trait with use Logger;. Create an instance with $s = new Service() and print echo $s->log("running") . "\n";.
Show example solution
string { ... } }. Then add class Service { use Logger; }. Create $s = new Service(); and call $s->log("running").
Example solution:
<?php
// Define the Logger trait and use it in the Service class
trait Logger {
public function log(string $msg): string {
return "[LOG] " . $msg;
}
}
class Service {
use Logger;
}
$s = new Service();
echo $s->log("running") . "\n";
Test yourself
-
Where is the use TraitName; line written?
- When creating an instance with new
- Inside the trait definition
- Inside the class body, outside methods
- In parentheses right after the class name
Show answer
Inside the class body, outside methods — Correct. The use line goes inside the class body, as a separate block from methods.
-
Include the trait in the class
trait Greeter {
public function hello(): string {
return "Hello";
}
}
class User {
____ Greeter;
}
$u = new User();
echo $u->hello() . "\n";
Show answer
trait Greeter {
public function hello(): string {
return "Hello";
}
}
class User {
use Greeter;
}
$u = new User();
echo $u->hello() . "\n";
-
After class User { use Greeter; }, what does $u->hello() print?
- Hello
- Throws an error
- Greeter
- User
Show answer
Hello — Correct. use Greeter; injects hello() into User, so it prints Hello.
Next lesson: Multiple traits