In this episode of the PHP 8 tutorial, we will learn about PHP constants.
PHP Constants are like variables for a simple value, that value cannot be changed during the execution of PHP script.
By default constant names are case-sensitive. A valid constant name starts with a letter or underescore. A constant name cannot begin with dollar sign.
Compared to variables, constants are global. You can access constants from anywhere in the script.
How to create a PHP constant
Constants are created using a define() function. There are two mandatory and one optional arguments.
First argument is the name of the constant, second argument function takes for the constant value. The optional third argument sets the case-sensitivity.
Example of creating a PHP constant
<?php define("MY_FIRST_CONSTANT", "Hello world!"); echo MY_FIRST_CONSTANT; ?>
The const keyword
The const keyword can be used instead of the function define(). Here is the syntax.
const CONSTANT_NAME = value;
Here is an example of using the const keyword.
<?php const MY_FIRST_CONSTANT = "Hello world!"; echo MY_FIRST_CONSTANT; ?>
Leave a Reply