Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Boolean FALSE and TRUE be redefined

Tags:

php

I'm reading a book about PHP, and about using TRUE and FALSE, it says :

In fact, the lowercase versions are more stable, because PHP does not allow you to redefine them; the uppercase ones may be redefined

I tried to redefine TRUE and FALSE, and it didn't work!! I google redefining constants and found out that i need to use runkit_constant_redefine(), i don't have runkit extension installed so i can't try it on TRUE and FALSE..

My question is, Can TRUE, true, FALSE or false be redefined with or without runkit_constant_redefine() ?

like image 270
Karmen Sali Avatar asked Oct 23 '14 16:10

Karmen Sali


2 Answers

You can define different true and false in every namespace.

namespace foo;

define('foo\true', 0);
if (true) {
    echo 'This will be never printed.';
}
like image 187
Damian Polac Avatar answered Nov 16 '22 05:11

Damian Polac


Boolean true is defined as case-insensitive constant, with true being the default notation.

 define("true", 1, 1);

That means it will work in any other casing as well, be it TRUE or True or TrUe or tRUE.

What your book alludes to is redefining the constant in another case variant again. Which you can. All but the lowercase true are open spots in the constant lookup table.

With e.g. define("True", 2) it will take precedence over the lowercase-defined true which would substitute for the other cases else.

It's pointless advice from your book anyway. Even though you could declare a dozen variants for the boolean constants, nobody actually does that. The presumed "more stable" reasoning is practically bogus. Prefer the notation that's more readable or matches the existing coding style.

like image 5
mario Avatar answered Nov 16 '22 07:11

mario