Advertisement

Google Ad Slot: content-top

PHP OOP - Traits

~1 min read · PHP
On this page

PHP - What are Traits?


  • A trait is a way to reuse methods across multiple classes without using inheritance.
  • Unlike abstract classes, traits do not require class extension.
  • PHP does not support multiple inheritance, but traits allow multiple classes to share functionality.
  • Traits are declared with the trait keyword:


Syntax:


<?php
  trait TraitName {
    // some code...
  }
?>


To use a trait in a class, you use the use keyword inside the class definition. 


Syntax:


<?php
  class MyClass {
    use TraitName;
  }
?>


Let's look at an example:

Example
showMessage(); // Output: Hello from the trait! ?>
Try it yourself

Explanation

  1. The MessageTrait trait defines a method showMessage().
  2. The MyClass uses the MessageTrait by using the use keyword.
  3. The showMessage() method is available in MyClass and can be called on its object.

PHP - Using Multiple Traits


You can use multiple traits in a class by separating them with commas.


Let's look at another example:

Example
walk(); // Output: I am walking! echo "
"; echo $person->sayHello(); // Output: Hello, I am a Human ?>
Try it yourself

Explanation

  • 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.