PHP 常量

define() vs const, constant arrays, class constants, and when to use constants.

Beginner
Key PointsA constant cannot be changed or undefined once set, and is global by default.

定义常量

PHP offers two ways: define() is a function evaluated at runtime; const is a language construct resolved at compile time.

PHP
<?php
define("SITE_NAME", "runoob");
const VERSION = "8.3";

echo SITE_NAME . " " . VERSION . "\n";
echo constant("SITE_NAME"), "\n";

var_dump(defined("SITE_NAME"));
var_dump(defined("SITE_URL"));
Output
runoob 8.3
runoob
bool(true)
bool(false)
Featuredefine()const
Where allowed任意位置,包括 if / 函数体内只能顶层或类内
Value type任意表达式,运行时求值编译期常量表达式
Speed稍慢(函数调用)稍快
Case-insensitivePHP 8 起已移除该参数始终敏感
Class constant不能直接定义可以
Constant names carry no $. $SITE_NAME is a different thing entirely — an undefined variable that silently yields nothing.

常量数组

Since PHP 7 constants may hold arrays, but elements must be constant expressions — no variables.

PHP
<?php
define("CONF", ["host" => "localhost", "port" => 3306]);
const PORTS = [80, 443, 8080];

echo CONF["host"] . ":" . CONF["port"], "\n";
echo count(PORTS), "\n";
echo implode(",", PORTS), "\n";
Output
localhost:3306
3
80,443,8080

类常量

Class constants belong to the class, not an instance, accessed via ClassName::CONST. PHP 8.3 adds typed constants.

PHP
<?php
class Config {
    const TIMEOUT = 30;
    public const RETRY = 3;
    final public const NAME = "demo";
}

class Child extends Config {
    // 继承来的常量可以直接用
    public function show(): string {
        return static::NAME . " timeout=" . self::TIMEOUT;
    }
}

echo Config::TIMEOUT + Config::RETRY, "\n";
echo (new Child())->show(), "\n";

$ref = new ReflectionClass("Config");
print_r($ref->getConstants());
Output
33
demo timeout=30
Array
(
    [TIMEOUT] => 30
    [RETRY] => 3
    [NAME] => demo
)
A final class constant cannot be overridden — better than a comment when a value is a contract.

魔术常量

There is also a family of interpreter-filled constants wrapped in double underscores, covered in the magic constants chapter.

  • __LINE__ —— current line number
  • __FILE__ / __DIR__ —— current file / directory
  • __FUNCTION__ / __CLASS__ / __METHOD__ —— current function / class / method
  • __NAMESPACE__ —— current namespace

什么时候用常量

  • 配置项 —— 数据库主机、超时秒数,改一处生效全局
  • 魔法数字 —— const MAX_UPLOAD = 10 * 1024 * 1024; 比到处写 10485760 强
  • 状态码 —— 用 const STATUS_OK = 200; 或 PHP 8 的枚举
  • 别用常量存会变的东西 —— 常量不能改,改需求时只能改代码

Friends & Partners