Class constants

A constant is, just like the name implies, a variable that can never be changed. When you declare a constant, you assign a value to it, and after that, the value will never change. Normally, simple variables are just easier to use, but in certain cases constants are preferable, for instance to signal to other programmers (or your self, in case you forget) that this specific value should not be changed during runtime.

Class constants are just like regular constants, except for the fact that they are declared on a class and therefore also accessed through this specific class. Just like with static members, you use the double-colon operator to access a class constant. Here is a basic example:
<?php
class User
{
    const DefaultUsername = "John Doe";
    const MinimumPasswordLength = 6;
}

echo "The default username is " . User::DefaultUsername;
echo "The minimum password length is " . User::MinimumPasswordLength;
?>
As you can see, it's much like declaring variables, except there is no access modifier - a constant is always publically available. As required, we immediately assign a value to the constants, which will then stay the same all through execution of the script. To use the constant, we write the name of the class, followed by the double-colon operator and then the name of the constant. That's really all there is to it.
<PreviousNext>
^ Back to Top