PHP OOP – Traits

The trait keyword is used to create traits. Traits are a way to allow classes to inherit multiple behaviours. Traits provide a way to reuse code across multiple classes without the need for inheritance, making the code easier to maintain and modify.

<?php
trait message1 {
  public function msg1() {
    echo "OOP is fun! ";
  }
}
trait message2 {
  public function msg2() {
    echo "OOP reduces code duplication!";
  }
}
class Welcome {
  use message1;
}
class Welcome2 {
  use message1, message2;
}
$obj = new Welcome();
$obj->msg1();
echo "<br>";
$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>

Leave a Reply