Advertisement

Google Ad Slot: content-top

PHP OOP - Traits


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
<?php
// Define a trait
trait MessageTrait {
public function showMessage() {
return "Hello from the trait!";
}
}
// Define a class that uses the trait
class MyClass {
use MessageTrait;
}
// Create an object of the class
$obj = new MyClass();
echo $obj->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
<?php
// First trait
trait Walk {
public function walk() {
return "I am walking!";
}
}
// Second trait
trait Speak {
public function sayHello() {
return "Hello, I am a " . get_class($this);
}
}
// Class using multiple traits
class Human {
use Walk, Speak;
}
$person = new Human();
echo $person->walk(); // Output: I am walking!
echo "<br>";
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.