How to Use PHP Traits

Matt Sparks - May 31 '18 - - Dev Community

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

. . . . . . . . . . . . . . . . . . .
Terabox Video Player