Defining traits
Learn to define a reusable set of methods with the trait keyword.
trait: a reusable method set
In PHP a class can inherit from only one class. But sometimes you want to share the same behavior across classes that are not related. For example, both Invoice and Email might need a log() method.
For this you use a trait. A trait is a reusable set of methods. It is declared like this: trait Logger { public function log() { ... } }. It looks like a class but cannot be instantiated with new.
After defining a trait you can verify it exists with trait_exists('Logger').
Trait body and example
A trait body looks like a class body. Inside it you can declare public, protected, private methods and properties. For example, a Greeter trait can carry a greeting behavior:
trait Greeter {
public function hello(): string {
return "Hello";
}
}A trait does not create an object on its own; its purpose is to be used by other classes after it is defined. For now, let's learn to define it and verify it with trait_exists.
Exercise Define your first trait
Define a Greeter trait. Inside it, add a public function hello(): string method that does return "Hello";. Then print echo trait_exists("Greeter") ? "defined" : "undefined"; and add a newline with echo "\n";.
Show example solution
string method returning "Hello". Then verify with trait_exists("Greeter").
Example solution:
<?php
// Define the Greeter trait
trait Greeter {
public function hello(): string {
return "Hello";
}
}
echo trait_exists("Greeter") ? "defined" : "undefined";
echo "\n";
Test yourself
-
Which keyword defines a trait?
- trait
- class
- module
- mixin
Show answer
trait — Correct. The trait keyword defines a trait; it looks like a class but cannot be instantiated with new.
-
Complete the trait declaration
trait ____ { public function hello(): string { return "Hello"; } }Show answer
trait Greeter { public function hello(): string { return "Hello"; } } -
Match the type to its definition
- trait
- reusable method set
- class
- creates instances
- abstract class
- cannot be instantiated
- interface
- declares a contract