PHP Basic Tutorial
MySQL Connection
PHP Advanced
PHP OOP
trait keyword:<?php
trait TraitName {
// some code...
}
?>
To use a trait in a class, you use the use keyword inside the class definition.
<?php
class MyClass {
use TraitName;
}
?>
Let's look at an example:
Try it yourself
MessageTrait trait defines a method showMessage().MyClass uses the MessageTrait by using the use keyword.showMessage() method is available in MyClass and can be called on its object.You can use multiple traits in a class by separating them with commas.
Let's look at another example:
Try it yourself
Walk and Speak are two separate traits, each with its own method.Human uses both traits via use Walk, Speak;.$person (instance of Human) can access both walk() and sayHello() methods—trait methods are treated as if they belong to the class.