PHP 8.2.20 Released!

Voting

: max(zero, two)?
(Example: nine)

The Note You're Voting On

Anonymous
4 years ago
The use of constant() (or some other method) to ensure the your_constant was defined is particularly important when it is to be defined as either `true` or `false`.

For example, taken from this Stackoverflow Question
https://stackoverflow.com/questions/5427886/php-undefined-constant-testing/56604602#56604602)

If `BOO` did NOT get defined as a constant, for some reason,

<?php if(BOO) do_something(); ?>

would evaluate to `TRUE` and run anyway. A rather unexpected result.

The reason is that PHP ASSUMES you "forgot" quotation marks around `BOO` when it did not see it in its list of defined constants.
So it evaluates: `if ('BOO')`...
Since every string, other than the empty string, is "truthy", the expression evaluates to `true` and the do_something() is run, unexpectedly.

If you instead use:
<?php if (constant(BOO)) do_something() ?>

then if `BOO` has not been defined, `constant(BOO)` evaluates to `null`,
which is falsey, and `if (null)`... becomes `false`, so do_something() is skipped, as expected.

The PHP behavior regarding undefined constants is particularly glaring when having a particular constant defined is the exception, "falsey" is the default, and having a "truthy" value exposes a security issue. For example,
<?php if (IS_SPECIAL_CASE) show_php_info() ?> .

There are other ways around this PHP behavior, such as
<?php if (BOO === true) do_something(); ?>
or
<?php if (defined('BOO') && BOO) do_something() ?>.

Note that only the version using `defined()` works without also throwing a PHP Warning "error message."

Here is a php repl.it demonstration:
https://repl.it/@sherylhohman/php-undefined-constants-beware-of-truthy-conversion?language=php_cli&folderId=

(disclosure: I also submitted an answer to the SO question linked to above)

<< Back to user notes page

To Top