7

Found an interesting piece of code in Symfony core

if ('' !== $host = $route->getHost()) {
    ...
}

The precedence of !== is higher than the = but how does it work logically? The first part is clear but the rest?

I've created a little sample but it's still not clear: sample

katona.abel
  • 771
  • 4
  • 12
  • 5
    Do it the save way `if ('' !== ($host = $route->getHost())) {` – JustOnUnderMillions Mar 06 '17 at 15:12
  • 1
    avoid problem using parenthesis .. – ScaisEdge Mar 06 '17 at 15:13
  • 1
    Possible duplicate of [JS vs PHP: assignment operator precedence when used with logical-or](http://stackoverflow.com/questions/32672016/js-vs-php-assignment-operator-precedence-when-used-with-logical-or) – Shira Mar 06 '17 at 15:16
  • 1
    Look at this http://sandbox.onlinephpfunctions.com/code/392fb443d315f2fe5e032a8e44c19c8fe3acdc5d maybe you get wired more or get it fully ;-) But for humanreadable and savety do it in the save way. By thw way this `$host = $route->getHost()` can be done a line before :-) – JustOnUnderMillions Mar 06 '17 at 15:17
  • 1
    I just don't get how can the $host = $route->getHost() part be executed first as the precedence is lower? – katona.abel Mar 06 '17 at 15:25

1 Answers1

3

The point is: The left hand side of an assignment has to be an variable! The only possible way to achieve this in your example is to evaluate the assignment first - which is what php actually does.

Adding parenthesis makes clear, what happens

'' !== $host = $route->getHost()
// is equal to
'' !== ($host = $route->getHost())
// the other way wouldn't work
// ('' != $host) = $route->getHost()

So the condition is true, if the return value of $route->getHost() is an non empty string and in each case, the return value is assigned to $host.

In addition, you could have a look a the grammer of PHP

...
variable '=' expr |
variable '=' '&' variable |
variable '=' '&' T_NEW class_name_reference | ...

If you read the operator precendence manual page carefully, you would see this notice

Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.

Philipp
  • 15,377
  • 4
  • 35
  • 52