How to Create and Access a Class Constant in PHP

php


In this article, we show how to create a class constant in PHP.

A constant is a value that is constant, it cannot change. It's the opposite of a variable that can change value. A constant is declared once and stays the same throughout the course of code.

A class constant is a constant found in a class.

This can be useful whenever you need a constant in object oriented programming such as in classes.

To create a constant in a class, you use the keyword const followed by the constant name and the value it is equal to.

The following code below creates a class constant and shows how to access this class constant in code. We do so by echoing out the value..



So the above code creates a class called mathematics.

In this class, we define a constant named PI, which is the distance around a circle when the diameter is equal to 1.

To create a constant, we simply use the keyword const, followed by the constant name. Normally constants will always be initialized at the time of declaration so we set its value equal to 3.14159265.

To access the class constant, you use the name of the class (in this case mathematics), followed by 2 colons (::), followed by the name of the constant (in this case PI).

In this code, we echo out the constant, so an echo precedes this code.

Usually by convention, constants are put in all uppercase. This is just a coding convention, not a necessity. But this helps to differentiate constants from variables.

Running the PHP code above, we get the following output shown below.

Actual PHP Output


3.14159265


HTML Comment Box is loading comments...