Trait declaration and usage
📖 Scenario: Imagine you are building a simple PHP application where multiple classes need to share a common method to greet users. Instead of repeating the same code in each class, you will use a trait to keep your code clean and reusable.
🎯 Goal: You will create a trait with a greeting method, then use this trait in two different classes. Finally, you will create objects of these classes and call the greeting method to see the shared behavior.
📋 What You'll Learn
Create a trait named
Greeter with a method sayHello() that returns the string "Hello from Trait!"Create a class named
Person that uses the Greeter traitCreate a class named
Robot that uses the Greeter traitCreate an object of
Person and an object of RobotCall the
sayHello() method on both objects and print the results💡 Why This Matters
🌍 Real World
Traits help you reuse code easily when multiple classes need the same functionality without repeating code.
💼 Career
Understanding traits is useful for writing clean, maintainable PHP code in real projects, especially in frameworks like Laravel that use traits extensively.
Progress0 / 4 steps