What is the defined method in PHP?

The defined method can be used to check if a constant exists or not.

defined(string $constant_name): bool

This method returns true if the constant is defined, otherwise it returns false.

Example

<?php
define('ONE', 1);
define('TWO', 2);
echo "IS ONE DEFINED defined : ";
var_dump(defined('ONE'));
echo "\nIS TWO DEFINED defined : ";
var_dump(defined('TWO'));
echo "\nIS TEST defined : ";
var_dump(defined('TEST'));
echo "\nTesting Predefined Constants \n";
echo("-------------------------");
echo "\nIS PHP_VERSION defined : "; // predefined constant
var_dump(defined('PHP_VERSION'));
?>

In the code above, we have created two constants, ONE and TWO. We used the defined method to check if the constants are available. For the constants ONE, TWO, and PHP_VERSION we will get true. For the TEST constant, we will get false since it is neither a predefined constant nor is it one defined by the program.

Free Resources