PHP常量与枚举定义最佳实践

常量和枚举用于定义固定不变的值。PHP8.1引入的枚举让常量管理更规范。今天说说常量和枚举的用法。

PHP常量用define或const定义。

```php
define('APP_NAME', 'MyApp');
define('APP_VERSION', '1.0.0');
define('MAX_UPLOAD_SIZE', 10 * 1024 * 1024);

const DB_HOST = 'localhost';
const DB_PORT = 3306;
const API_TIMEOUT = 30;

echo APP_NAME . "\n";
echo DB_HOST . "\n";
?>

类常量用const定义。

```php
class User
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_BANNED = 'banned';

const ROLES = ['admin', 'editor', 'user'];

public const MAX_LOGIN_ATTEMPTS = 5;
private const SALT_LENGTH = 32;
}

echo User::STATUS_ACTIVE . "\n";
echo User::MAX_LOGIN_ATTEMPTS . "\n";
?>

PHP8.1枚举。

```php
enum OrderStatus: string
{
case Pending = 'pending';
case Paid = 'paid';
case Shipped = 'shipped';
case Delivered = 'delivered';
case Cancelled = 'cancelled';

public function label(): string
{
return match ($this) {
self::Pending => '待支付',
self::Paid => '已支付',
self::Shipped => '已发货',
self::Delivered => '已签收',
self::Cancelled => '已取消',
};
}

public function isActive(): bool
{
return $this !== self::Cancelled;
}
}

$status = OrderStatus::Paid;
echo $status->label() . "\n";
echo $status->isActive() ? '活跃' : '不活跃' . "\n";

// 从数据库值创建
$dbStatus = 'paid';
$status = OrderStatus::from($dbStatus);
echo $status->label() . "\n";
?>

常量数组的定义。

```php
const CONFIG = [
'database' => ['host' => 'localhost', 'port' => 3306],
'redis' => ['host' => 'localhost', 'port' => 6379],
];

define('ERROR_MESSAGES', [
400 => '错误请求',
401 => '未授权',
404 => '未找到',
500 => '服务器错误',
]);

echo ERROR_MESSAGES[404] . "\n";
?>

常量和枚举的使用原则。常量用于不变的值如配置、状态码。枚举用于有限的一组选项如订单状态、用户角色。枚举比常量更安全,因为类型检查可以确保只使用有效的值。

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐