constant
常量一旦被定义,就不能再改变或取消定义,常量的作用域是全局,可以在任何位置访问
- define 是函数
- const 是关键字
define
define('常量名称', '常量值', '是否不区分大小写,默认区分')- define函数的参数可以通过变量传递,可以在任何位置调用,但是不能作用于类成员变量
- 当常量名是通过变量设定,可以使用constant(变量名获取)
define('CONSTANT', 'this is test');//定义一个常量
echo CONSTANT;
----------------------------------------------------
$constantVariable= 'TEST';//通过变量定义常量名
define($constantVariable, 'this is test');
echo TEST;//不可行,报错
echo constant($constantVariable);//正确获取方式
this is test
----------------------------------------------------
class test {
public $constant = define();//不可行
define();//不可行
function test() {
define('CONSTANT', 'this is test');//定义一个常量
}
}
const
const 常量名=常量值- const不可以在语句和函数中定义,使用场景:在类中定义
- 常量名不可以是变量
$variable = 200;
const ERROR_CODE = $varable;//不可以通过变量赋值
----------------------------------------------------------
const ERROR_CODE = 200;//不建议这样定义常量,使用define更常见
echo ERROR_CODE;
200;
-----------------------------------------------------------
class name {
const ERROR_CODE = 200;
public function getConstant() {
self::ERROR_CODE;//在本类中获取定义的常量
}
}
echo name::ERROR_CODE;//直接获取类中定义的常量
-----------------------------------------------------------
use name;
name::ERROR_CODE;//直接获取类中定义的常量
系统预定义常量
| 系统预定义常量 | 常量值 |
|---|---|