PHP Constants are similar to variables except that they cannot change. They can’t change since constants are stored in the read-only-data segment. Why would you not want to keep data constant? A good example is when you want to store database connection information. You do not want to accidentally change the connection information somewhere later in your code and accidentally sever the database connection.
How do we define constants in our code? With the define function. define() accepts two arguments:
- The first argument is the constant name.
- The second argument is the constant value.
<?php define("DB_USERNAME", "dances_with_squirrels");
define("DB_PASSWORD", "hakuna_matata");?>
Constants names are by convention declared using all uppercase characters. This is purely so that the person that’s looking at your code, yourself included, can see effortlessly which values are constants.
Constants follow the same naming convention as variables. Constants can start with a letter or underscore, followed by a sequence of letters, underscores, and/or numbers. The main difference is that constants do not start with the dollar sign like variables do.
To call the constant that we just created, we’ll use just the constant name that we provided inside of our define function.
<?php echo DB_USERNAME; // outputs dances_with_squirrels?>
A practical use for a constant can be to store the folder location for a particular sequence of images. For example, let’s say that we are storing pictures of bears inside of /images/animals/bears/ folder. It would get pretty repetitive for us to keep adding the entire folder path to each image. What if we mess up writing it? What if, later down the road, we want to change our code and move everything from /images/animals/bears/ to /images/animals/mammals/bears/. Depending on how many images we have, we would have to modify each location; by using a constant, you would have to modify only one location. The reason that you would want to use a constant is because you don’t want to change that folder location accidentally somewhere later in your code.
<?php define("IMG_FOLDER", "/images/animals/bears/");echo IMG_FOLDER . "black_bear.jpg";?>
As of PHP 7, you can actually store multi-dimensional arrays inside of constants.
<?php define("CAR", [
"year" => 1995,
"make" => "Toyota",
"model" => "Supra",
"specs" => [
"hp" => 1000,
"tq" => 1200
]
]);var_dump(CAR);?>
You don’t have to use the define function when creating constants. You can prefix the constant name with the const keyword. I prefer the const keyword.
<?php const FAV_FOOD = "Burger";echo FAV_FOOD;?>
PHP also has magic constants, such as __DIR__. I‘m going to write a separate article on just magic constants so we’ll discuss those then.