PHP Constants
- A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script.
- Do not use the
define()
method for declaring a constant as it does not work within classes. - Constants defined in a class are READ-ONLY and STATIC (shared by all instances of the class).
- Constants Manual (php.net)
// Define a constant.
const MY_CONSTANT = 'a value';
// Use a constant.
echo MY_CONSTANT; // Prints "a value."
// Use with a class.
class Foo {
const MY_CONST = 'bar';
// Use a constant in a method.
public function get_my_const() {
return self::MY_CONST;
}
// Call a constant dynamically.
public function get_constant($name) {
return constant("self::{$name}");
}
}
// Use statically.
echo Foo::MY_CONST; // prints 'bar'
// Use with an instantiated class.
$foo = new Foo();
echo $foo->get_my_const(); // prints 'bar'
echo $foo->get_constant('MY_CONST'); // prints 'bar'
echo $foo::MY_CONST; // prints 'bar'