PHP define() Function

What is PHP define() Function?

In PHP, define() function is used to define a constant. If you want to define a variable whose value shouldn’t be changed during the execution of the script and you want to access its value throughout the script, then define a constant to store the value. In real, you can’t change a constant value during the script execution too.

Syntax:

define(CONSTANT_NAME, constant_value, case_insensitive)

Parameters:

The function has two required parameters and one optional parameter-

CONSTANT_NAME (Required): Name of the constant.

constant_value (Required): Value of the constant. It must be a scalar value (int, float, string, bool, or null) (Check example 1) or an array (Check example 2)

case_insensitive (Optional): This parameter has one value – FALSE (as of PHP 8.0.0). It sets the CONSTANT_NAME as case-sensitive (Check example 3). So, if this parameter is set as FALSE, then “LANGUAGE” and “language” are considered as two different constants. The default behavior (which means if you don’t mention this parameter) of the parameter is case-sensitive (Check example 4) which is the same as the FALSE.

Note: Before PHP 7.3.0, the value TRUE indicated case-insensitive which means “LANGUAGE” and “language” were considered as same constant. As of PHP 8.0.0, if you mention TRUE to this parameter, you’ll get a warning.

Return Values:

The function returns-

  • TRUE – if it successfully defines a constant.
  • FALSE – if it fails to defines a constant.

Examples:

Example 1:

<?php
define ("LANGUAGE", "php");
echo "Name of the programming language is: " . LANGUAGE;
?>

Output:

Name of the programming language is: php

Example 2:

<?php
define('LANGUAGES', array(
    'PHP',
    'JAVA',
    'PYTHON'
));
echo "Third language is: " . LANGUAGES[2];
?>

Output:

Third language is: PYTHON

Explanation:

The value of the constant LANGUAGE is an array. To retrieve the third element by the constant LANGUAGES, we used LANGUAGES[2].

Example 3:

<?php
define ("FRAMEWORK", "Laravel", FALSE);
echo "Name of the programming language is: " . FRAMEWORK;
?>

Output:

Name of the programming language is: Laravel

Explanation:

Setting the third parameter (case-sensitive) as FALSE, the constant becomes case sensitive. So, you have to keep the constant case same (line 2 & 3).

Example 4:

<?php
define ("VERSION", 8.3);
echo "Name of the programming language is: " . version;
?>

Output:

Fatal error: Uncaught Error: Undefined constant “version” in D:\xampp\htdocs\phpExercise\34. define.php:9 Stack trace: #0 {main} thrown in D:\xampp\htdocs\php\define.php on line 3

Explanation:

As we changed the case of the constant (line 3), we get “Undefined constant” error.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP () Function

define() is the function to define a constant in your PHP script. It is a miscellaneous type built-in function.

Reference:

https://www.php.net/manual/en/function.define.php