PHP Function Reference

PHP define() Function



The PHP define() function is used to define a named constant at runtime.

Syntax

define(constant_name, value, case_insensitive)

Parameters

constant_name Required. Specify the name of the constant.
value

Required. Specify the value of the constant.

In PHP 5, value must be a scalar value (int, float, string, bool, or null). In PHP 7, array values are also accepted.
case_insensitive Optional. If set to true, the constant will be defined case-insensitive. The default behavior is case-sensitive.

Note: By using this function, it is possible to define constants with reserved or even invalid names, whose value can only be retrieved with constant() function. However, this is not recommended.

Note: It is possible to define resource constants, it is not recommended and may cause unpredictable behavior.

Note: Defining case-insensitive constants is deprecated as of PHP 7.3.0 and removed as of PHP 8.0.0.

Return Value

Returns true on success or false on failure.

Example: define() example

The example below shows the usage of define() function.

<?php
//defining a constant
define("Greeting", "Hello world!");

//displaying the value of the constant
echo Greeting."\n";

//raises an error
echo GREETING."\n";
?>

The output of the above code will be:

Hello world!

PHP Fatal error:  Uncaught Error: Undefined constant "GREETING" in Main.php:10
Stack trace:
#0 {main}
  thrown in Main.php on line 10

Example: constant with array value

Consider the example below where this function is used to define a constant with array value.

<?php
//defining a constant with array value
define("COLORS", array("Red", "Green", "Blue"));

//displaying the value of the constant
echo COLORS[0]."\n";
echo COLORS[1]."\n";
echo COLORS[2]."\n";
?>

The output of the above code will be:

Red
Green
Blue

Example: constant with reserved names

Consider one more example where this function is used to define a constant with reserved names.

<?php
var_dump(defined('__LINE__'));
var_dump(define('__LINE__', 'Hello World!'));

//displaying the defined value of __LINE__
var_dump(constant('__LINE__'));
//the value of reserved word __LINE__
var_dump(__LINE__);
?>

The output of the above code will be:

bool(false)
bool(true)
string(12) "Hello World!"
int(8)

❮ PHP Miscellaneous Reference