PHP defined() why is it returns false, even if the constant is defined?

php

Solution

The short answer is; Add quotation marks

Because you're not referring to the constant named `TEST` - you're referring to whatever `TEST` contains.

Wrapped out, this is what you're doing (the code is right - there is no `123` constant):

define('TEST', 123);

var_dump( defined(TEST) ); // turns into the below statement
var_dump( defined(123) ); // false - no 123 constant

Refer to the constant name instead (enclose it in quotes):

define('TEST', 123);

var_dump( defined('TEST') ); // true, the TEST constant is indeed defined
//                ^    ^ Quotation marks are important!

What if my constant is in a namespace?

If your constant is defined in a namespace, you must include it in the constant name.

namespace Some\Namespace;

const MY_CONST = 'value';

var_dump( defined('MY_CONST') ); // false unless another constant has been defined
var_dump( defined('Some\Namespace\MY_CONST'); // true

Problem

I can't understand why this code is executed is not the way I want. ``` define('TEST', 123); echo TEST; echo "\n"; var_dump( defined(TEST) ); ``` print: ``` 123 bool(false) ```

Original source