时间:2021-07-01 10:21:17 帮助过:20人阅读
常量的值只能是标量数据(boolean,integer,float 和 string)或 null。
常量一旦被定义,就不能被重新定义或者取消定义。
有两种定义方式:
用define()函数来定义常量
define('STATUS', 3); // 如果第三个参数设置为true,则大小写不敏感
echo STATUS;
用const关键字来定义常量
const NAME = 4;
echo NAME;
还可以用函数 constant() 来获取常量的值。
使用defined()函数,检查某个名称的常量是否存在。
2. 类常量
可以在类中定义常量,常量的值必须是一个定值,不能是变量,类属性或其它操作(如函数调用)的结果。但在PHP5.6中,对常量进行了增强,允许常量计算,允许使用包含数字、字符串字面值和常量的表达式结果来定义const常量。常量的值也可以为一个数组,但不能是变量。
定义类常量只能使用const关键字。
class MyClass {
const AB = 2;
public function showConstant(){
echo self::AB;
}
}
echo MyClass::AB;
$obj = new MyClass();
$obj -> showConstant();
MyClass::showConstant();
$className = 'MyClass';
echo $className::AB;实例:
/**
* 1、define(name,value,case_insensitive) 自定义全局常量, 默认大小写敏感
* 2、const 定义类常量。
* 3、常量名前不要使用”$”
* 4、常量的命名一般全部使用大写字母。
*/
//定义全局常量 LANGUAGE
define('LANGUAGE','中国');
echo language;//language
echo LANGUAGE;//中国
//定义全局常量 CN
define('CN','中国',TRUE);
echo CN;//中国
echo cn;//中国
//定义类常量
class ConstTest{
const VERSION = '1.0';
function ConstTest(){
//类内部使用“self::常量名”调用,不能使用$this
echo 'self::VERSION='.self::VERSION;
}
}
//实例化 ConstTest,目的是调用构造函数
new ConstTest();
//外部调用类常量,通过“类名::常量名”直接调用,无需实例化。
echo 'VERSION='.(ConstTest::VERSION);
echo '<br>';
//array get_defined_constants ([ bool $categorize = false ] ) 返回所有已定义的常量
//print_r(get_defined_constants(true));
//bool defined ( string $name ) 检查该名称的常量是否已定义。
echo defined('cn')?'true':'false';打印结果:
language 中国 中国 中国 self::VERSION=1.0 VERSION=1.0 true
以上就是php自定义常量与类常量区别分析的详细内容,更多请关注Gxl网其它相关文章!