Create a constant in PHP to store a fixed value
We’ve defined a variable, but we haven’t changed the value of it yet. Variables are meant to be able to be changed or updated at any time.
For example, we can change our $numPosts
variable by adding the previous value of $numPosts
to 10. This will output 20 when we refresh the page.
<?php $title = 'My Blog'; $numPosts = 10; $numPosts = $numPosts + 10; $numPostsDisplay = "$numPosts posts"; ?> <h1><?= $title ?></h1> <h2><?= $numPostsDisplay ?></h2>
This is sort of a silly example, but you will without a doubt have increasingly complex calculations going on somewhere in your code, eventually.
Variables are meant to be modified or updated. But sometimes you want to make sure a value never changes. In this case, you can assign the value to a constant rather than a variable.
There are two types of constants: global constants & local constants.
Global constants are defined with the define()
function, and are executed at run time. For this reason, they cannot be used within classes, which always require the use of local constants. You don’t know about classes yet, but we’ll touch base on them later on.
define()
accepts two arguments. The first is the name of the constant, and its common convention to use UPPER_SNAKE case. Here, we’ll define
define('MIN_NUM_POSTS', 0);
The second param is the value we wish to assign the constant.
At this point, we cannot re-assign the value of MAX_NUM_POSTS to another value. Doing so will cause a notice to be thrown:
define('MIN_NUM_POSTS', 0); define('MIN_NUM_POSTS', 1);
Since we pass the name of the constant as a string, that means constants defined this way can use something like string interpolation to create dynamically named constants, and even defined within loops. Since the define()
function is executed at runtime, that means they can also be used within if statements.
Any value, include advanced data types, can also be assigned using define()
. This differs from the const
keyword which is used to define local constants.
Theconst
keyword has received increasing functionality over the years, and has a simpler, easier to read syntax. We can create local constants using const
just like PHP variables.
Let’s create another constant for MAX_NUM_POSTS:
const MAX_NUM_POSTS = 100;
Note that creating a local constant looks a lot like defining a regular PHP variable. This format was initially created just for classes, but since defining a constant like this is a lot simpler and easier to read than using the define()
function, it’s now the preferred method of creating constants.
Class constants are only available within the class they are created in, and we’ll learn more about that later. It’s worth noting that const
cannot be used within if
statements or loops, so there is still some precedence to using define()
instead for specific scenarios.