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.
<?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");
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?