Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 624
Alex Avatar asked Mar 25 '11 02:03

Alex


People also ask

What is undefined constant in PHP?

Referring to a class constant without specifying the class scope.

Is constant defined PHP?

Constants are like variables except that once they are defined they cannot be changed or undefined.

Does PHP have 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.


2 Answers

// 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.

like image 179
alex Avatar answered Oct 06 '22 18:10

alex


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.

like image 26
Anomie Avatar answered Oct 06 '22 18:10

Anomie