What is the difference between while (true)
vs while (\true)
and most Importantly can anyone clarify why boolean
are affected by namespace in PHP
?
The while loop in python runs until the "while" condition is satisfied. The "while true" loop in python runs without any conditions until the break statement executes inside the loop.
Why does while distinguish the two? It's emitting a LOAD_GLOBAL (True) for each True , and there's nothing the optimizer can do with a global. So, while distinguishes 1 and True for the exact same reason that + does.
while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually!
While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever.
In PHP true
, false
and null
are constants, which are protected from being overwritten in namespaces. As such the following is invalid code:
namespace Foo; const true = false; // Cannot redeclare constant 'true'
It is still possible to overwrite such a constant using ''define()'':
namespace Foo; define('Foo\true', false); var_dump(true); // bool(false)
However this isn't supported functionality (it might be called a bug) and PHP is free to assume that true
cannot be overwritten. For example usage of true
in a constexpr context will not be affected by the above definition:
// Note: This uses eval() to make sure the define() runs before the constexpr // constant resolution happens namespace Foo; define('Foo\true', false); var_dump(eval('namespace Foo; static $t = true; return $t;')); // bool(true)
The reason why the substitution happens in the constexpr case, but not in the "normal" case is a bug in the implementation. For constexprs the substitution happens before name resolution, whereas for normal code it happens after name resolution.
The correct implementation would be to always substitute after name resolution, but specifically account for true
, false
and null
during the substitution. I plan to fix this for PHP 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With