PHP defined() Function

What is PHP defined() Function:

In PHP, defined() function is used to check whether a constant is defined or not. In your PHP script, before defining a constant it is safe to check whether it has already been defined or not to avoid issues.

Syntax:

defined(CONSTANT_NAME)

Parameters:

The function has one required parameter –

CONSTANT_NAME (Required): Name of the constant.

Return Values:

The function returns-

  • TRUE – if the constant has been defined.
  • FALSE – if the constant hasn’t been defined.

Examples:

Example 1:

<?php
define ("LANGUAGE", "php");
var_dump( defined("LANGUAGE"));
?>

Output:

bool(true)

Example 2:

<?php
if( !defined("SITENAME")) define("SITENAME", "Schools of Web");
echo 'Site name is: "' . SITENAME . '"';
?>

Output:

Site name is: “Schools of Web”

Explanation:

Before defining the constant SITENAME, we checked whether it has been defined by defined() function.

Practical Usages of PHP defined() Function:

To avoid collision, before defining a constant, you can use defined() function to check whether it has been defined already.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP defined() Function

PHP defined() function is built-in misc. function. In almost all your PHP application, you’ll always define some constants. And, defined() function facilitates you to check the existence of a constant.

Reference:

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