Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP conditional assignment

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

like image 921
katona.abel Avatar asked Mar 06 '17 15:03

katona.abel


People also ask

What is conditional assignment operators in PHP?

PHP Conditional Assignment OperatorsReturns the value of $x. The value of $x is expr1 if expr1 exists, and is not NULL. If expr1 does not exist, or is NULL, the value of $x is expr2.

What is a conditional assignment?

Definition: Conditional assignment refers to transferring rights of the life insurance policy by the life insurance owner to someone else under some terms and conditions. The policyholder is the assignor, and the person to whom the policy is assigned is called the assignee.

What is === in PHP?

=== Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

Does PHP have +=?

The + operator is the addition operator. += will add numeric values. Save this answer.

Does PHP have ternary?

The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.


1 Answers

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.

like image 168
Philipp Avatar answered Oct 10 '22 15:10

Philipp