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.
1 2 3 4 5 6 7 8 9 |
<?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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
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:
1 2 3 4 5 |
class HorrorFilm { use ArrayOrJson; ... |
Putting it all together:
1 2 3 4 5 6 7 8 9 |
$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:
1 2 3 |
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!"}" |