// define('DOCROOT', realpath(dirname(__DIR__)));
// good
const DOCROOT = realpath(dirname(__DIR__));
// PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in
why error?
// define('DOCROOT', realpath(dirname(__DIR__)));
// good
const DOCROOT = realpath(dirname(__DIR__));
// PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in
why error?
A constant can be defined two ways in PHP,
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.
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.
$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.
}
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;
Check this site: http://www.php.net/manual/en/language.constants.php
const
definition must be inside the scope of one class.