In this tutorial, you will learn about PHP Constants step by step. So, without much to do, let’s get started.
Constants are like variables except that when they are defined, they can’t be changed or undefined.
In this tutorial, you will learn-
In this article, you will learn-
PHP Constants
A consistent is an identifier (name) for a easy value. The value can’t be changed at some stage in the script.
A valid consistent name begins with a letter or underscore (no $ sign before than the consistent name).
Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the consistent
• case-insensitive: Specifies whether the consistent name should be case-insensitive. Default is false
Example
Create a constant with a case-sensitive name:
<!DOCTYPE html> <html> <body> <?php // case-sensitive constant name define("GREETING", "Welcome to Worldofitech.com!"); echo GREETING; ?> </body> </html>
Example
Create a constant with a case-insensitive name:
<!DOCTYPE html> <html> <body> <?php // case-insensitive constant name define("GREETING", "Welcome to Worldofitech.com!", true); echo greeting; ?> </body> </html>
PHP Constant Arrays
In PHP7, you could create an Array regular the use of the define() function.
Example
Create an Array constant:
<!DOCTYPE html> <html> <body> <?php define("cars", [ "Honda", "BMW", "Toyota" ]); echo cars[0]; ?> </body> </html>
Constants are Global
Constants are automatically global and can be used across the entire script.
Example
This example uses a constant inside a function, even if it is defined outside the function:
<!DOCTYPE html> <html> <body> <?php define("GREETING", "Welcome to Worldofitech.com!"); function myTest() { echo GREETING; } myTest(); ?> </body> </html>
READ NEXT
This is about PHP Constants, and we hope you have learned something from this tutorial and share your opinion about this tutorial. What do you think about it, and if you think this tutorial will help some of your friends, do share it with them.