Can you explain the concept of PHP traits

PHP traits are a mechanism for code reuse in single inheritance languages like PHP. Traits allow developers to create reusable sets of methods that can be included in multiple classes. This helps to avoid code duplication and promotes clean architecture, as traits can encapsulate behavior that isn't tied to a specific class hierarchy. They are particularly useful when you want to apply the same functionality across different classes that don't share a common parent class.

Example of PHP Traits

<?php trait Logger { public function log($message) { echo "[Log]: " . $message . "<br>"; } } trait UserSettings { public function setSettings($settings) { echo "Settings updated for user: " . $settings . "<br>"; } } class User { use Logger, UserSettings; } $user = new User(); $user->log("User has logged in."); $user->setSettings("dark mode enabled"); ?>

PHP traits code reuse single inheritance methods classes behavior functionality