How to Use PHP Traits
Tags: php, webdev
Published: 2018-05-31 23:33:43

---
title: How to Use PHP Traits
published: true
description: 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](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) and more maintainable.
tags: php, webdev
cover_image: http://developmentmatt.com/wp-content/uploads/2018/05/villa-3237114_1280.jpg
---

[PHP Traits](http://php.net/manual/en/language.oop5.traits.php) 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
<?php

trait RobotSkillz
{
    public function speak(string $output)
    {
        echo $output;
    }
}
```

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.

```php
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;
    }
}
```

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

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

    public function asJson() : string
    {
        return json_encode($this->asArray());
    }
}
```

We add this trait to our class:

```php
class HorrorFilm
{
    use ArrayOrJson;
    
    ...

```

Putting it all together:

```php
$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());
```

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!"}"
```

Originally Posted on [DevelopmentMatt](https://developmentmatt.com/how-to-use-php-traits/)