常量和變量有如下不同:
- 常量前面沒有美元符號($);
- 常量只能用 define() 函數定義,而不能通過賦值語句;
- 常量可以不用理會變量的作用域而在任何地方定義和訪問;
- 常量一旦定義就不能被重新定義或者取消定義;
- 常量的值只能是標量。
<?php
define('MIN_VALUE', '0.0'); // RIGHT - Works OUTSIDE of a class definition.
define('MAX_VALUE', '1.0'); // RIGHT - Works OUTSIDE of a class definition.
//const MIN_VALUE = 0.0; RIGHT - Works both INSIDE and OUTSIDE of a class definition.
//const MAX_VALUE = 1.0; RIGHT - Works both INSIDE and OUTSIDE of a class definition.
class Constants
{
//define('MIN_VALUE', '0.0'); WRONG - Works OUTSIDE of a class definition.
//define('MAX_VALUE', '1.0'); WRONG - Works OUTSIDE of a class definition.
const MIN_VALUE = 0.0; // RIGHT - Works INSIDE of a class definition.
const MAX_VALUE = 1.0; // RIGHT - Works INSIDE of a class definition.
public static function getMinValue()
{
return self::MIN_VALUE;
}
public static function getMaxValue()
{
return self::MAX_VALUE;
}
}
?>
和使用 define() 來定義常量相反的是,使用 const 關鍵字定義常量必須處於最頂端的作用區域,因爲用此方法是在編譯時定義的。這就意味着不能在函數內,循環內以及 if 語句之內用 const 來定義常量。