Traits

Last updated

What is Traits?

Traits is a concept in PHP that allows code reusability by enabling developers to create reusable pieces of code which can be used in classes to extend functionality. They are a way to reduce intricacies of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes.

Here's an example how to use a Trait:

trait Greeting {
    public function sayHello() {
        return "Hello";
    }
}
class User {
    use Greeting;
}
$user = new User();
echo $user->sayHello(); // Outputs: Hello

In the above code snippet, the Greeting trait is being used in the User class, and we are able to use its methods as if they were defined in the User class.

Free resources to learn Traits

More in stage 12: PHP-FIG

Traits: common questions

Can I learn Traits in Hindi?

This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Traits in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.

Is this Traits tutorial for beginners?

It is lesson 86 of 120 in the free PHP roadmap, in stage 12, PHP-FIG. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.

Still confused? Ask me