const PHP Parse错误

时间:2014-01-30 16:06:03

标签: php

// define('DOCROOT', realpath(dirname(__DIR__)));
// good

const DOCROOT = realpath(dirname(__DIR__));
// PHP Parse error:  syntax error, unexpected '(', expecting ',' or ';' in

为什么会出错?

3 个答案:

答案 0 :(得分:4)

一个常量可以在PHP中用两种方式定义,

  1. 使用const关键字

    您不能以这种方式将功能结果,甚至变量分配给常量。常量的值(以这种方式定义),必须是固定值,如整数或字符串。

  2. 使用define()

    通过这种方式,您可以将任何值或变量或任何函数的结果分配给常量。

  3. 重要说明: 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.
    }
    

答案 1 :(得分:2)

类常量必须是固定值。不是某些功能的结果。只有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;

答案 2 :(得分:1)

检查此网站:http://www.php.net/manual/en/language.constants.php

const定义必须在一个类的范围内。