如何在PHP函数中创建常量变量,例如使用C ++ const关键字?
const int t = 10;
a = 11; // compile error
Run Code Online (Sandbox Code Playgroud)
可能需要提高可读性而不使其易于出错。例如,当一个人需要一个用于长命名对象属性的快捷方式时,他为此创建了一个变量,而另一个人在函数中间修改了此变量,从而导致错误。
类常量:
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
通常:
define("const_name", "const_value");
echo const_name;
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/language.oop5.constants.php
http://php.net/manual/zh/function.constant.php