Constants
A constant is an identifier or name given for a simple value. The constants value cannot change during the execution of the script (except for magic constants).
The standard naming convention for constants are always uppercase.
We can define constants a couple of ways. The first is by using the define() function.
define("FOO", "something");
echo FOO; // Prints out "something"
The other way is by using the “const” keyword:
const MIN_VALUE = 0.0;
The define() method, if used in OOP should be used outside the class definition whereas const should be used inside the class definition.
<?php
define("FOO", "Something"); // Correct
const BAR = "Some other thing"; // Wrong
class MyClass
{
const CONSTANT = 'Constant value'; // Correct
define("BAZ", "Something else"); // Wrong
}
Class constant are by default public in nature but you cannot assign them a visibility as this results in a syntax error.
<?php
class MyClass
{
const CONSTANT = 'constant value';
public const OTHER_CONSTANT = 'other constant value'; // Syntax error
}
$class = new MyClass();
echo $class::CONSTANT; // Works
echo $class::OTHER_CONSTANT; // Doesn't work
Magic constants
PHP provides a large number of predefined constants to any script which it runs. Some of the constants change depending on where they are used. e.g. __LINE__ depends on the line that it’s used on in your script. Some of the magic constants are listed below:
Note: This article is based on PHP version 5.5.