Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable in if statement expression

I ran across some interesting code today. I tried to find out if this is a feature of PHP or if I am missing something, but was unable to find anything on Google. Probably because I don't know the name of it.

Code

if($logo = \Repositories\Logo::getLogoData($id)){
     $logo_href = $logo->link;
}

The variable $logo is not being set anywhere else. It seems like the expression in this if statement is checking to see if the that class method is returning anything and simultaneously setting the variable $logo to be used in the statement.

Is this true? If so, what in the world is this called!?!

like image 398
Chris Bier Avatar asked Apr 18 '13 20:04

Chris Bier


2 Answers

You can make an assignment like that in a conditional. What happened logically is that the value is assigned to $logo and then $logo is evaluated as to whether it is truthy. If it is truthy, the code in the conditional executes.

You will oftentimes see this sort of assignment/evaluation in the case of looping through database result sets, but generally I would suggest that it should be avoided outside such a common use case for sake of clarity in reading g code.

like image 75
Mike Brant Avatar answered Oct 16 '22 22:10

Mike Brant


Yes, this is a feature. It's like:

$a=$b=5;

But in this case, imagine the bool result of if as var $a.

However, IDE's are used to complain about solutions like this because of == vs. = as a very common possible bug source.

like image 29
Dodo Avatar answered Oct 16 '22 22:10

Dodo