One of the major problem is PHP is a single inheritace language. But in real life we might face a case where we need to use multiple behaviour in a class. Or we might thinking how can we apply multiple inhertence. To solve this problem php introduce traits.
Let's discuss this by giving an example:
using normal inheritance:
<?php
class Car {
class Car {
public function lambo() {
echo "This is lambo car!";
echo "This is lambo car!";
echo "<br>";
}
}
}
}
class Car1 extends Car {
public function ferari() {
echo "This is ferari car!";
echo "This is ferari car!";
echo "<br>";
}
}
}
}
// inherited from Car and only single inheritance occured
class Car2 extends Car1 {
public function audi() {
echo "This is audi car!";
}
}
$car = new Car2;
$car -> lambo();
$car -> ferari();
$car -> audi();
?>
$car -> audi();
?>
using traits:
<?php
trait Car {
trait Car {
public function lambo() {
echo "This is lambo car!";
echo "This is lambo car!";
echo "<br>";
}
}
}
}
trait Car1 {
public function ferari() {
echo "This is ferari car!";
echo "This is ferari car!";
echo "<br>";
}
}
}
}
// multiple behaviour or multiple inheritance occured
class Car2 {
use Car, Car1; // using multiple traits
public function audi() {
echo "This is audi car!";
}
}
$car = new Car2;
$car -> lambo();
public function audi() {
echo "This is audi car!";
}
}
$car = new Car2;
$car -> lambo();
$car -> ferari();
$car -> audi();
?>
$car -> audi();
?>
