By convention, all constant names are uppercase. Do  NOT prepend a constant  name with $, unlike variables. Constant's values, once defined, never change.

PHP Constant

By convention, all constant names are uppercase. Do NOT prepend a constant name with $, unlike variables. Constant's values, once defined, never change.

Const and Define()

Here is one way to create a constant in PHP, using the const construct:

const YEAR_BORN = 1983; echo "I was born in the year ".YEAR_BORN; //output: I was born the year 1983

And another way to create the same constant using the built-in function define();

define('YEAR_BORN', 1983); echo "I was born in the year ".YEAR_BORN; //output: I was born the year 1983

Trying to put the constant name inside double quotes just like variable names, will not get the desired result because PHP wouldn't know you're referring to a constant and will simply interpret literal text."

const YEAR_BORN = 1983; echo "I was born in the year YEAR_BORN"; //output: I was born in the year YEAR_BORN

So make sure to always concatenate constant names with a dot (.)

Constants In a Class Definition

Though both const and define() are both correct ways to define a constant, using define() within class definition won't work:

class Life { define ( 'CHANGE', true ); //wrong, only works outside of class definition const CHANGE = true; //correct, works inside of class definition }

Also, the way to access constant's values when we're dealing with classes is different. Inside of a class definition, we have to use the "self" keyword followed by two semi-colons, followed by the constant name:

class Life { const CHANGE = true; public static function getChange() { return self::CHANGE; } }

Then, if we wanted to access constant's value outside of a class definition, we can use two ways:

//1) Type class name, two semi-colons, and constant name exactly $answer = Life::CHANGE; //2) Type class name, two semi-colons, and method name with parenthesis $answer = Life::getChange();

We are able to get the value of our constant using getChange() method because it was defined as a static method. All static methods in PHP that are defined in a class are also accessed with double semi-colon just like a constant, though don't forget the parenthesis at the end.

There are no set methods like setChange() within the class definition because once constants are defined and initialized, they can't be changed.