如何使用 PHP Traits

2025-06-07

如何使用 PHP Traits

PHP Traits是实现代码复用的绝佳工具。它允许开发人员编写可在任意数量的类中使用的方法,从而保持代码的 DRY 原则,并使其更易于维护。

定义 PHP 特征

特征的定义方式与类的定义方式大致相同。

<?php

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

您会注意到我们声明的trait是 而不是class

PHP 特征示例

假设我们有大量与电影类型相关的类。每个类都有一些公共属性,我们希望以数组或 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

现在,我们将创建一个特征,添加我们需要的方法,并且可以在我们所有的类中重复使用。

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

我们将这个特征添加到我们的类中:

class HorrorFilm
{
    use ArrayOrJson;

    ...

Enter fullscreen mode Exit fullscreen mode

总结一下:

$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

输出:

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

最初发表于DevelopmentMatt

文章来源:https://dev.to/mattsparks/how-to-use-php-traits-459m
PREV
Matt 最喜欢的 Visual Studio Code 扩展
NEXT
Object.freeze() 变得困难🥶❄️