PHP 8.2 新特性之 traits 中的常量

作者: 温新

分类: 【PHP基础】

阅读: 1717

时间: 2023-02-20 15:59:43

hi,我是温新,一名 PHPer

<?php

trait HelpTool
{
    // trait 中定义常量
    public const STATUS = 'draft';
    // protected,private 修饰的常量,只有自己可以访问
    protected const SEX = 'male';

    public function getStatus(): string
    {
        // trait 中使用 self 来调用自身的常量
        return 'public: ' .  self::STATUS . ' protected: ' . self::SEX;
    }
}

class User
{
    use HelpTool;
}

class Human
{
    use HelpTool;

    // 若重复定义会报错
    // public const STATUS = 'pending';
}

// 通过类名访问 trait 中的常量
echo User::STATUS;
echo Human::STATUS;

Traits 中使用常量,需要注意如下几点:

  • 不能使用 trait 的名称来访问常量,无是从内部还是从外部;
  • 只有 public 修饰的常量可以被其他类访问;
  • 常量的访问可以使用 类名::常量 的形式访问。
请登录后再评论