Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `while (true)` vs `while (\true)`?

Tags:

What is the difference between while (true) vs while (\true) and most Importantly can anyone clarify why boolean are affected by namespace in PHP ?

like image 472
Baba Avatar asked Sep 24 '14 18:09

Baba


People also ask

What is the difference between while true and while?

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.

Is while 1 the same as while true?

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.

What is the meaning of while true?

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!

When should we use while true?

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.


1 Answers

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.

like image 50
NikiC Avatar answered Oct 06 '22 08:10

NikiC