Junior — Middle
Can you explain what Traits are and how they are used in programming?
sobes.tech AI
Answer from AI
Traits in PHP are a mechanism for code reuse in classes. They allow including a set of methods into multiple classes without inheritance. This is useful when you want to share common functionality among different classes that are not related by inheritance.
Example of using Traits:
trait Logger {
public function log(string $message) {
echo "Log: $message";
}
}
class User {
use Logger;
public function create() {
// user creation logic
$this->log('User created');
}
}
$user = new User();
$user->create();
Thus, Traits help avoid code duplication and provide a convenient way to organize common methods.