php

What is define() Function in PHP

PHP is a popular language used by developers worldwide to create strong and effective web applications. One of the reasons PHP is so versatile is that it has a built-in special function called define() that allows developers to assign a specific value to a symbol, and that value cannot be changed while the program is running.

We will discuss the detail of the define() function, syntax, and usage in this guide.

What is a define() Function in PHP?

The define() is a built-in function in PHP used to create constants. Constants are like variables, but once they are defined within the program their values remain the same. The constants in PHP are useful for storing values that remain constant throughout the program’s execution.

Syntax

The syntax for using the define() function in PHP is as follows:

define('CONSTANT_NAME', value, case-insensitive)

The define function accepts the three parameters, a CONSTANT_NAME that specifies the variable name of the constant, value that defines the value of the constant, and case_insensitive is a parameter that specifies whether the name of the constant should be case-insensitive. This is the optional parameter and has two possible values, either True or False, the True is for the case-insensitive variable name, and the False is for the case-sensitive name. The default behavior of the function is case-sensitive, while the case-insensitive is no longer supported in PHP.

Example 1

In the following example, we have defined a constant variable named CONSTANT with the value LinuxHint. We then printed the value of CONSTANT, the first echo statement will print the value and the second will display an error. Because the function is case-sensitive:

<?php
define("CONSTANT", "LinuxHint");
echo CONSTANT ."\n";
echo Constant;
?>

Example 2

You can also assign the value of one constant to another by simply referencing the original constant when defining the new constant.

For example:

<?php
define("STR", "LinuxHint");
define("NEW_STR", STR);

echo STR;
echo "\n";
echo NEW_STR;
?>

The given PHP code defines a constant named “STR” with the value “LinuxHint” and another constant named “NEW_STR” that is assigned the value of the “STR” constant. The code then outputs the values of both constants using the echo statement.

Bottom Line

PHP has a unique way of performing actions, and it is quite different from other popular programming languages. In PHP, there are two different ways to define a constant, one is using the const keyword and the other is using the define() function. The constant in PHP can be used anywhere in the code and their value remains the same throughout the execution of the program.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.