PHP OOP - Traits


PHP - What are Traits?

PHP supports only one legacy: a child class can inherit from one parent only.

So, what if the class needs more discipline? OOP features solve this problem.

Symbols are used to advertise methods that can be used in most classes. Symbols can have invisible methods and methods that can be used in most classes, and methods can have any access controller (public, private, or secure).

Symbols are advertised with the feature keyword:


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

To use a feature in the classroom, use a keyword:


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

Let's look at an example:


Example
<?php
trait message1 {
public function msg1() {
    echo "OOP is fun! ";
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();
?>

Example Explained

Here, we announce one feature: message1. Then, we built a classroom: Welcome. The class uses the attribute, and all symbols will be available in the classroom.

If other classes need to use the msg1 () function, just use the message1 feature in those classes. This reduces code duplication, because there is no need to repeat the same process over and over again.


PHP - Using Multiple Traits

Let's look at another example:


Example
<?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();
?>

Example Explained

Here, we announce two aspects: message1 and message2. Then, we created two classes: Welcome and Welcome2. The first category (Welcome) uses the message1 element, and the second category (Welcome2) uses both message symbols1 and message2 (most symbols are separated by commas).