常量是一个简单值的标识符(名字)。常量的范围是全局的。常量默认为大小写敏感。传统上常量标识符总是大写的
常量名遵循php 标签命名规则,字母或下划线开始,后面跟着字母,数字或下划线。正则表达式为:[a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*
字母指的是 a-z,a-z,以及从 127 到 255(0x7f-0xff)的 ascii 字符。
example #1 合法与非法的常量名 <?php // 合法的常量名define("foo", "something");define("foo2", "something else");define("foo_bar", "something more");// 非法的常量名 define("2foo", "something"); // 下面的定义是合法的,但应该避免这样做:(自定义常量不要以__开头) // 也许将来有一天php会定义一个__foo__的魔术常量 // 这样就会与你的代码相冲突define("__foo__", "something"); ?>
语法
定义常量:
用 define() 函数定义常量。用 defined() 函数检查是否定义了某常量。 用 const 关键字在类定义之外定义常量(php 5.3.0)。
使用 const 关键字定义常量必须处于最顶端的作用区域,因为用此方法是在编译时定义的。这就意味着不能在函数内,循环内以及 if 语句之内用 const 来定义常量。
常量只能包含标量数据(boolean,integer,float 和 string)。可以定义 resource 常量, 但会造成不可预料的结果。 动态常量名,用函数 constant() 获取常量值。用 get_defined_constants() 可以获得所有 已定义的常量列表。
常量和变量有如下不同:
常量前面没有美元符号($); 常量只能用 define() 函数定义,而不能通过赋值语句; 常量可以不用理会变量的作用域而在任何地方定义和访问; 常量一旦定义就不能被重新定义或者取消定义; 常量的值只能是标量。 *常量和(全局)变量在不同的名字空间中。这意味着例如 true 和 $true 是不同的。
example #1 定义常量 <?php define("constant", "hello world.");echo constant; // outputs "hello world."echo constant; // 输出 "constant" 并发出一个提示级别错误信息 ?>
example #2 使用关键字 const 定义常量 <?php // 以下代码在 php 5.3.0 后可以正常工作const constant = 'hello world'; echo constant; ?>
魔术常量
8个 php 的“魔术常量”,随着它们在代码中的位置改变而改变。
__line__ 文件中的当前行号。 __file__ 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。 自 php 4.0.2 起,__file__ 总是包含一个绝对 路径(如果是符号连接,则是解析后的绝对路径),而在此之前的版本有时会包含一个相对路径。 __dir__ 文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__file__)。除非是根目录,否则目 录中名不包括末尾的斜杠。(php 5.3.0中新增) __class__ 类的名称(php 4.3.0 新加)。自 php 5 起本常量返回该类被定义时的名字 (区分大小写)。在 php 4 中该值总是小写字母的。 类名包括其被声明的作用区域(例如 foo\bar)。注意自 php 5.4 起 __class__ 对 trait 也起作用。当用在 trait 方法中时,__class__ 是 调用 trait 方法的类的名字。 __method__ 类的方法名(php 5.0.0 新加)。返回该方法被定义时的名字(区分大小写)。 __namespace__ 当前命名空间的名称(区分大小写)。此常量是在编译时定义的 (php 5.3.0 新增)。
/* __function__ and __method__ as in php 5.0.4 is that __function__ returns only the name of the function while as __method__ returns the name of the class alongwith the name of the function */<?php class trick{ function doit() { echo __function__; } function doitagain() { echo __method__; } }$obj=new trick();$obj->doit(); // output will be ---- doit$obj->doitagain(); // output will be ----- trick::doitagain
相关推荐:
thinkphp中常用的系统常量和系统变量
thinkphp5 加载静态资源路径与常量的方法
php7内核剖析4之局部变量,全局变量,常量
以上就是【php手册】常量的详细内容。
