DEV Community

Cover image for How to Use PHP Traits
Matt Sparks
Matt Sparks

Posted on

How to Use PHP Traits

PHP Traits are a great tool for code reuse. They allow developers to write methods that can be used in any number of classes, keeping your code DRY and more maintainable.

Define a PHP Trait

Traits are defined much in the same way as classes.

<?php

trait RobotSkillz
{
    public function speak(string $output)
    {
        echo $output;
    }
}
Enter fullscreen mode Exit fullscreen mode

You'll notice that we're declaring a trait rather than a class.

A PHP Trait Example

Let's pretend we have a large number of classes related to film genres. Each class has public properties that we would like to return as either an array or JSON.

class HorrorFilm
{
    public $genre;
    public $length;
    public $rating;
    public $releaseDate;
    public $title;

    public function getGenre() : string
    {
        return $this->genre;
    }

    public function getLength() : int
    {
        return $this->length;
    }

    public function getRating() : string
    {
        return $this->rating;
    }
    public function getReleaseDate() : string
    {
        return $this->releaseDate;
    }

    public function getTitle() : string
    {
        return $this->title;
    }

    public function setGenre(string $genre)
    {
        $this->genre = $genre;
    }

    public function setLength(int $minutes)
    {
        $this->length = $minutes;
    }

    public function setRating(string $rating)
    {
        $this->rating = $rating;
    }

    public function setReleaseDate(string $date)
    {
        $this->releaseDate = $date;
    }

    public function setTitle(string $title)
    {
        $this->title = $title;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, we'll create a trait that adds the methods we need and can be reused across all of our classes.

trait ArrayOrJson
{
    public function asArray() : array
    {
        return get_object_vars($this);
    }

    public function asJson() : string
    {
        return json_encode($this->asArray());
    }
}
Enter fullscreen mode Exit fullscreen mode

We add this trait to our class:

class HorrorFilm
{
    use ArrayOrJson;

    ...

Enter fullscreen mode Exit fullscreen mode

Putting it all together:

$film = new HorrorFilm;
$film->setTitle('Kill All Humans!');
$film->setGenre('Slasher');
$film->setLength(124);
$film->setRating('R');
$film->setReleaseDate('November 2, 2019');

var_dump($film->asArray());
var_dump($film->asJson());
Enter fullscreen mode Exit fullscreen mode

Output:

array(5) { ["genre"]=> string(7) "Slasher" ["length"]=> int(124) ["rating"]=> string(1) "R" ["releaseDate"]=> 

string(16) "November 2, 2019" ["title"]=> string(16) "Kill All Humans!" } string(105) "{"genre":"Slasher","length":124,"rating":"R","releaseDate":"November 2, 2019","title":"Kill All Humans!"}"
Enter fullscreen mode Exit fullscreen mode

Originally Posted on DevelopmentMatt

Top comments (8)

Collapse
 
megusta420 profile image
hi panda

So, guys, what do you think about that traits in PHP is not good practice because of a couple of arch reasons (better using of abstract classes)? Also, what do you think about why for example Vue JS proposes mixins as good practice? Discuss.

Collapse
 
paulthebaud profile image
Paul Thébaud

I don't know Vue JS mixins, but about PHP, here is my opinion :
Traits are not a bad practice, but they must be used carefully. I mean, you can use them for several things (I think about the RefreshDatabase trait in Laravel testing env), but it is not a good practice to use them to add property in your class (such as adding a name on your class Person for exemple).

Collapse
 
megusta420 profile image
hi panda

Hm, are comments that previous posters posted were removed? I asked there about the opinion of one member, but after refreshing found that there just only 2 comments. Was it bug or what?

Collapse
 
paulthebaud profile image
Paul Thébaud

Yes. Someone disagree with me, I click on the "read and reply" link, and got a 404 ...

Collapse
 
mattsparks profile image
Matt Sparks

It appears so, my comments were removed as well.

Collapse
 
megusta420 profile image
hi panda

That is not nice :( I thought there is a free platform for developers with nice SPA design and without removing of any discussions in comments.

Collapse
 
paulthebaud profile image
Paul Thébaud

Traits <3 Laravel is a good example of using Traits to remove code duplication :)

Collapse
 
jjjjcccjjf profile image
endan

Nice!