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

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

why error?

Brad
  • 159,648
  • 54
  • 349
  • 530
Shniperson
  • 549
  • 4
  • 9

3 Answers3

6

A constant can be defined two ways in PHP,

  1. Using const keyword

    You can't assign the result of function, or even a variable to a constant in this way. the value of the constant (defined this way), must be a fixed value, like an integer, or a string.

  2. Using define()

    in this way, you can assign any value or variable or result of any function to your constant.

Important note : define() Works OUTSIDE of a class definition.

Examples

$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.
}
Alireza Fallah
  • 4,609
  • 3
  • 31
  • 57
2

A class constant has to be a fixed value. Not the result of some function. Only global constants set by define may contain results of a function.

Global Constants: http://www.php.net/manual/en/language.constants.php

Class Constants: http://www.php.net/manual/en/language.oop5.constants.php

Sample for a global constant:

define("FOO",     "something");
echo FOO;

Sample for a class constant:

class Test {
    const FOO = "Hello";
}

echo Test::FOO;
ToBe
  • 2,667
  • 1
  • 18
  • 30
  • This is completely wrong. You can define a constant to be whatever value you want. – Brad Jan 30 '14 at 16:09
  • No. Only if it is a static value that is fixed during compile time. – ToBe Jan 30 '14 at 16:09
  • Youre right, this rule is only applicable to class cnstants, not global ones. tested and confirmed. I updated my answer. – ToBe Jan 30 '14 at 16:12
1

Check this site: http://www.php.net/manual/en/language.constants.php

const definition must be inside the scope of one class.

Brad
  • 159,648
  • 54
  • 349
  • 530