Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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)
like image 742
Ruslan Avatar asked Jul 29 '13 10:07

Ruslan


People also ask

How do you check if a constant is defined in PHP?

Checking if a PHP Constant is Defined This can be achieved using the PHP defined() function. The defined() function takes the name of the constant to be checked as an argument and returns a value of true or false to indicate whether that constant exists.

What are the main difference between const vs 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.

What is the function of define in PHP?

Definition and Usage The define() function defines a constant. Constants are much like variables, except for the following differences: A constant's value cannot be changed after it is set.


2 Answers

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!
like image 147
h2ooooooo Avatar answered Sep 22 '22 02:09

h2ooooooo


use have call it wrong

define('TEST', 123);
echo TEST;
echo "\n";
var_dump( defined(TEST) );//provide The constant name you are providing 123 so it not defined
//correct call would be
var_dump( defined('TEST') );
like image 40
Rajeev Ranjan Avatar answered Sep 25 '22 02:09

Rajeev Ranjan