DEV Community

Cover image for PHP Traits
AI_Dosage
AI_Dosage

Posted on

2

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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
 
ai_dosage profile image
AI_Dosage

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs