PHP get_defined_constants() Function
Last Updated :
28 Feb, 2023
The get_defined_constants() function is an inbuilt function in PHP that returns the name of all the constants that are currently defined with their values in the form of an associative array.
Syntax:
get_defined_constants(bool $categorize = false): array
Parameter: This function accepts single parameter that is described below:
- $categorize: This function returns a multidimensional array that contains categories in the keys for the first dimension & constants with their values will be in the second dimension.
Return Value: This function returns an array in the form of keys and values, i.e, key name => value.
Example 1: In the below example, we will be called the get_defined_constants() function and print the associative array. Here, the get_defined_constants prints all constant as well as user-defined constants.
PHP
<?php
define( "MY_FIRST_CONSTANT" ,1);
print_r(get_defined_constants(true)) ;
?>
|
Output:
Array (
[Core] => Array
(
[E_ERROR] => 1
[E_RECOVERABLE_ERROR] => 4096
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_STRICT] => 2048
[E_DEPRECATED] => 8192
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_USER_DEPRECATED] => 16384
[E_ALL] => 32767
[DEBUG_BACKTRACE_PROVIDE_OBJECT] => 1
[DEBUG_BACKTRACE_IGNORE_ARGS] => 2
)
[user] => Array
(
[MY_FIRST_CONSTANT] => 1
)
)
Example 2: In the below example, we will print only user define constant user get_defined_constants() function.
PHP
<?php
define( "MY_FIRST_CONSTANT" ,1);
print_r(get_defined_constants(true)[ "user" ]) ;
?>
|
Output:
Array
(
[MY_FIRST_CONSTANT] => 1
)
Reference: https://www.php.net/manual/en/function.get-defined-constants.php
Share your thoughts in the comments
Please Login to comment...