php分享三十三:常量
一:常量定义
1:在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量)
2:常量默认为大小写敏感
3:命名规则:用正则表达式是这样表达的:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
在这里,字母指的是 a-z,A-Z,以及从 127 到 255(0x7f-0xff)的 ASCII 字符。
4:
如果使用了一个未定义的常量,PHP 假定想要的是该常量本身的名字,如同用字符串调用它一样(CONSTANT 对应 "CONSTANT")。此时将发出一个 E_NOTICE 级的错误。参见手册中为什么 $foo[bar] 是错误的(除非事先用 define()将 bar 定义为一个常量)。如果只想检查是否定义了某常量,用 defined() 函数。
settings.php <?php // Debug mode define('DEBUG',false); ?> test.php <?php include('settings.php'); if (DEBUG) { // echo some sensitive data. } ?>
If for some reason settings.php doesn't get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The solution is to evaluate it. Like so:
settings.php <?php // Debug mode define('DEBUG',0); ?> test.php <?php include('settings.php'); if (DEBUG == 1) { // echo some sensitive data. } ?>
5:heredoc中的常量不能被解释,如果需要调用,可以把常量封装到一个函数里,返回调用
There is a way to access a constant in heredoc. Here is the example: <?php define("__STR",'constant.string.defined'); function heredocGetConstant($constant) { return constant($constant); } $heredocGetConstant = 'heredocGetConstant'; $my_string = <<<EOT This is my constant printed from heredoc: {$heredocGetConstant('__STR')} EOT; echo $my_string; Output: This is my constant printed from heredoc: constant.string.defined
6:It is perfectly valid to use a built-in PHP keyword as a constant name - as long as you the constant() function to retrieve it later:
define('echo', 'My constant value'); echo constant('echo'); // outputs 'My constant value'
7:动态的常量可以用constant()返回
8:常量和(全局)变量在不同的名字空间中。这意味着例如 TRUE
和 $TRUE 是不同的。
二:魔术常量(8个)
__FUNCTION__; __FILE__; __LINE__; __NAMESPACE__; __TRAIT__; __CLASS__; __METHOD__; __DIR__;
二:类常量const
1:接口(interface)中也可以定义常量
2:从php5.6开始常量可以用标量表单式了
3:类常量可以被覆盖
it's possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by 'get_called_class' method:
abstract class dbObject { const TABLE_NAME='undefined'; public static function GetAll() { $c = get_called_class(); return "SELECT * FROM `".$c::TABLE_NAME."`"; } } class dbPerson extends dbObject { const TABLE_NAME='persons'; } class dbAdmin extends dbPerson { const TABLE_NAME='admins'; } echo dbPerson::GetAll()."<br>";//output: "SELECT * FROM `persons`" echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `admins`"
二:const和define定义常量的区别
1:和使用 define() 来定义常量相反的是,使用 const 关键字定义常量必须处于最顶端的作用区域,因为用此方法是在编译时定义的。这就意味着不能在函数内,循环内以及 if 语句之内用 const 来定义常量。
2:类常量中不能有变量,define中可以用
The const keyword will not allow anything that may have to be "processed": $color = "red"; const RED = "This is the color $color"; //Doesn't work define(strtoupper($color), "This is the color $color") // Works fine