@sherylhohman/

php-undefined-constants-beware-of-truthy-conversion

PHP CLI

How to properly test for falsey/truthy value of a constant in PHP. HINT: undefined constants get type converted to truthy string of same nam

fork
loading
Files
  • main.php
main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
define('FOO', true);
if (FOO) {
    echo "\nI am FOO!\n";
}
echo "\n--------------------\n";

// Boo is undefined
echo "\n    assume undefined constant is falsey: \n";
if (BOO) {
    echo "\n    BOO!\n";
}
echo "\n--------------------\n";

// Boo is undefined
echo "\n    use constant(): \n";
if (constant(BOO)) {
    echo "\n    I am BOO!\n";
} else {
  echo "\n    Boo wasn't defined.\n";
}
echo "\n--------------------\n";

echo "\n    use defined() && BOO:  \n";
if (defined('BOO') && BOO) {
    echo "\n    I am BOO!\n";
} else {
  echo "\n    Boo wasn't defined.\n";
}
echo "\n--------------------\n";

echo "\n    use ===:        \n";
if (BOO === true) {
    echo "\n    I am BOO!\n";
} else {
  echo "\n    Boo wasn't defined.\n";
}
echo "\n--------------------\n";

echo "\n    use ==:        \n";
if (BOO == true) {
    echo "\n    BOO!\n";
} else {
  echo "\n    Boo wasn't defined.\n";
}
echo "\n--------------------\n";