Alex Alex - 1 month ago 19
PHP Question

PHP undefined constant testing

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?

Answer

BOO will be coerced into the string BOO, which is not empty, so it is truthy.

CodePad.

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.