Trait #

一、Trait基础 #

1.1 定义Trait #

php
<?php
trait Loggable
{
    public function log(string $message): void
    {
        echo "[" . date('Y-m-d H:i:s') . "] $message\n";
    }
}

1.2 使用Trait #

php
<?php
class UserService
{
    use Loggable;
    
    public function create(array $data): User
    {
        $this->log("Creating user");
        return new User($data);
    }
}

1.3 多个Trait #

php
<?php
trait Loggable
{
    public function log(string $message): void
    {
        echo "[LOG] $message\n";
    }
}

trait Timestampable
{
    public function touch(): void
    {
        $this->updatedAt = new DateTime();
    }
}

class User
{
    use Loggable, Timestampable;
}

二、冲突解决 #

2.1 insteadof #

php
<?php
trait A
{
    public function foo(): void
    {
        echo "A::foo\n";
    }
}

trait B
{
    public function foo(): void
    {
        echo "B::foo\n";
    }
}

class Example
{
    use A, B {
        A::foo insteadof B;
        B::foo as bar;
    }
}

$example = new Example();
$example->foo();
$example->bar();

2.2 as修改可见性 #

php
<?php
trait ExampleTrait
{
    private function secret(): void
    {
        echo "Secret\n";
    }
}

class Example
{
    use ExampleTrait {
        secret as public;
    }
}

三、抽象方法 #

php
<?php
trait Validator
{
    abstract protected function getRules(): array;
    
    public function validate(array $data): bool
    {
        $rules = $this->getRules();
        
        return true;
    }
}

class UserForm
{
    use Validator;
    
    protected function getRules(): array
    {
        return [
            'name' => 'required',
            'email' => 'required|email'
        ];
    }
}

四、实际应用 #

4.1 软删除 #

php
<?php
trait SoftDeletes
{
    protected ?DateTime $deletedAt = null;
    
    public function delete(): void
    {
        $this->deletedAt = new DateTime();
    }
    
    public function restore(): void
    {
        $this->deletedAt = null;
    }
    
    public function isDeleted(): bool
    {
        return $this->deletedAt !== null;
    }
}

4.2 时间戳 #

php
<?php
trait HasTimestamps
{
    public DateTime $createdAt;
    public DateTime $updatedAt;
    
    public function touch(): void
    {
        $this->updatedAt = new DateTime();
    }
}

五、总结 #

本章学习了:

  • Trait定义和使用
  • 多个Trait
  • 冲突解决
  • as修改可见性
  • 抽象方法

下一章将学习静态成员。

最后更新:2026-03-26