// define('DOCROOT', realpath(dirname(__DIR__)));
// good
const DOCROOT = realpath(dirname(__DIR__));
// PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in为什么会出错?
发布于 2014-01-30 16:14:57
在PHP中可以用两种方式定义常量,
const关键字
您不能以这种方式将函数的结果,甚至是变量分配给常量。常量的值(以这种方式定义),必须是一个固定值,如整数或字符串。重要注意事项: define()在类定义之外工作。
示例
$var = "String";
const CONSTANT = $string; //wrong
const CONSTANT = substr($var,2); //wrong
const CONSTANT = "A custom variable"; //correct
const CONSTANT = 2547; //correct
define("CONSTANT", "A custom variable"); //correct
define("CONSTANT", 2547); //correct
define("CONSTANT", $var); //correct
define("CONSTANT", str_replace("S","P", $var)); //correct
class Constants
{
define('MIN_VALUE', '0.0'); //wrong - Works OUTSIDE of a class definition.
}发布于 2014-01-30 16:07:40
类常量必须是一个固定值。不是某种功能的结果。只有define设置的全局常量才能包含函数的结果。
全局常量:http://www.php.net/manual/en/language.constants.php
类常量:http://www.php.net/manual/en/language.oop5.constants.php
全局常量的样本:
define("FOO", "something");
echo FOO;类常量的示例:
class Test {
const FOO = "Hello";
}
echo Test::FOO;发布于 2014-01-30 16:07:29
查看本网站:http://www.php.net/manual/en/language.constants.php
const定义必须在一个类的范围内。
https://stackoverflow.com/questions/21461493
复制相似问题