In PHP if I define a constant like this:
define('FOO', true);
if(FOO) do_something();
The method do_something
gets executed as expected.
But if I don't define the BOO
constant below:
if(BOO) do_something();
Then do_something
also gets executed. What's going on here?
Referring to a class constant without specifying the class scope.
Constants are like variables except that once they are defined they cannot be changed or undefined.
There is no such syntax defined for an undefined index in php because it a kind of error we get when we try to access the value or variable in our code that does not really exist or no value assign to them, and we are trying to access its value somewhere in the code.
// BOO has not been defined
if(BOO) do_something();
BOO
will be coerced into the string BOO
, which is not empty, so it is truthy.
This is why some people who don't know better access an array member with $something[a]
.
You should code with error_reporting(E_ALL)
which will then give you...
Notice: Use of undefined constant HELLO - assumed 'HELLO' in /t.php on line 5
You can see if it is defined with defined()
. A lot of people use the following line so a PHP file accessed outside of its environment won't run...
<?php defined('APP') OR die('No direct access');
This exploits short circuit evaluation - if the left hand side is true, then it doesn't need to run the right hand side.
If you enable error logging, you'll see an error like the following:
PHP Notice: Use of undefined constant BOO - assumed 'BOO' in file at line N
What's happening is that PHP is just arbitrarily assuming that you meant to use 'BOO' and just forgot the quotes. And since strings other than ''
and '0'
are considered "true", the condition passes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With