Traits
PHP allows single inheritance only, A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way.It can have all access modifiers.
You may ask yourself why would we need traits
while we have Interfaces
?
The difference is interfaces only have abstract methods. A trait has methods that are abstract and also defined.
To declare a trait use the trait
keyword.
<?php
trait Person{
public function talk(){
echo "Hello,call later ";
}
public function walk(){
echo "I am driving";
}
}
class Driver{
use Person;
}
$driver = new Driver();
$driver->talk();
$driver->walk();
Using Multiple Traits
<?php
trait Model {
public function carModel() {
echo 'Volvo ';
}
}
trait Year {
public function manufactureYear() {
echo '2014';
}
}
class DefineVehicle {
use Model, Year;
public function DescribeVehicle() {
echo 'The Vehicle type is:';
}
}
$car = new DefineVehicle();
$car->DescribeVehicle();
$car->carModel();
$car->manufactureYear();
?>
?>
Top comments (3)
Traits are something I was recently made aware of. So often enough I just don't use them. So I read up on them after seeing this post. I saw someone explain that these are "language assisted copy and paste". That made sense to me, and kind of explains why I havens seen them so often.
One thing I find counter-intuitive is static properties on traits. Apparently each class using a trait will have their own instances of that property 🤯
php.net/manual/en/language.oop5.tr...
Interesting , i didn't know about this. Let me check it out in the documentation
The problem with traits is that you will not see the code in the classes itself, its on the fly copy&past magic and magic is mostly bad for the project in the long run.