The trait Keyword
The keyword trait
is used to create traits - a mechanism for code reuse in PHP. Traits are similar to classes but are intended for grouping functionality into small and understandable units. They can be included in classes using the keyword use
.
Syntax
trait TraitName {
// trait properties and methods
public function method1() {
// implementation
}
}
Example
Let's create a simple trait and connect it to a class:
<?php
trait Logger {
public function log($message) {
echo "Logging: " . $message;
}
}
class User {
use Logger;
}
$user = new User();
$user->log("User created");
?>
Code execution result:
'Logging: User created'
Example
A class can use several traits simultaneously:
<?php
trait Timestamp {
public function getCurrentTime() {
return date('Y-m-d H:i:s');
}
}
trait Serializer {
public function toJson($data) {
return json_encode($data);
}
}
class Product {
use Timestamp, Serializer;
}
$product = new Product();
echo $product->getCurrentTime();
?>
Code execution result:
'2023-11-15 14:30:00'