DEV Community 👩‍💻👨‍💻

Cover image for PHP Traits
Samuel K.M
Samuel K.M

Posted on

PHP Traits

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();
Enter fullscreen mode Exit fullscreen mode

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

?>
?>
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
andersbjorkland profile image
Anders Björkland

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...

Collapse
 
bazeng profile image
Samuel K.M Author

Interesting , i didn't know about this. Let me check it out in the documentation

Collapse
 
suckup_de profile image
Lars Moelleken

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.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.