Traits in PHP provide a flexible way to reuse code across multiple classes without using inheritance. They help reduce duplication while keeping class hierarchies clean and simple.
insteadof and asA trait is declared using the trait keyword and included in a class using the use keyword. Traits cannot be instantiated directly.
// Defining a Logger trait for reusable logging logic
";
}
}
class User {
use Logger;
public function createUser($name) {
$this->log("User '$name' created.");
}
}
$user = new User();
$user->createUser("Alice");
?>
The User class reuses the log() method from the Logger trait, allowing logging without inheritance.
// Using multiple traits inside a single class
";
}
}
trait Validator {
public function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
}
class Admin {
use Logger, Validator;
public function createAdmin($email) {
if ($this->validateEmail($email)) {
$this->log("Admin with email $email created.");
} else {
$this->log("Invalid email: $email");
}
}
}
$admin = new Admin();
$admin->createAdmin("admin@example.com");
$admin->createAdmin("wrong-email");
?>
Logger trait and reuse it in User and Admin classesinsteadof