Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php is it possible to determine if a constant is user defined?

Tags:

php

I know that in general I can check if a constant is defined with the following:

defined('MY_CONSTANT')
defined('PHP_EOL')

The first one is my own user-defined constant. The 2nd one is created by php. Both can be checked with defined() and return a boolean value.

My question is.. is there a way to determine whether it is a user-defined constant or a php-created constant? For example, the MY_CONSTANT should return some equivalent of "user defined" and PHP_EOL should return some equivalent of "php-defined".

like image 985
slinkhi Avatar asked Nov 05 '13 00:11

slinkhi


People also ask

Why would someone choose to use a constant instead of a variable in their PHP script?

You use a CONSTANT when you know a value will never be changed. You use a variable when you want a value to be changed. You should use constants if you want to ensure that the value will not/cannot get changed anywhere after it's been defined.

How is constant defined in a PHP script?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.

How do you check for a constant?

To check if constant is defined use the defined function. Note that this function doesn't care about constant's value, it only cares if the constant exists or not. Even if the value of the constant is null or false the function will still return true .

What is difference between constant and define in PHP?

The basic difference between these two is that const defines constants at compile time, whereas define() defines them at run time. We can't use the const keyword to declare constant in conditional blocks, while with define() we can achieve that.


2 Answers

Use get_defined_constants() with a parameter of true to return a categorized array of all constants.

User-defined constants are under the user key:

print_r(get_defined_constants(true));
// outputs:
// Array (
//    [Core] => Array (
//      [PHP_EOL] => 1
//    )
//    [user] => Array (
//      [MY_CONSTANT] => 1
//    )
// )
like image 144
Jason McCreary Avatar answered Oct 20 '22 19:10

Jason McCreary


See get_defined_constants

http://php.net/manual/en/function.get-defined-constants.php

$CheckConst = 'MY_CONSTANT';
$is_user_defined = isset(get_defined_constants (true)['user'][$CheckConst]);
like image 21
Ralph Ritoch Avatar answered Oct 20 '22 18:10

Ralph Ritoch