Alex Alex - 11 months ago 78
PHP Question

PHP undefined constant testing

In PHP if I define a constant like this:

define('FOO', true);
if(FOO) do_something();

The method
gets executed as expected.

But if I don't define the
constant below:

if(BOO) do_something();

also gets executed. What's going on here?

Answer Source

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.