Frage

here is something weird to me.

Code 1:

if($city = Cities::find_by_id($city_id)) {
  var_dump($city);
}

This returns: object(Cities)#6 (7) {...}, ordinary

Code 2:

if($city = Cities::find_by_id($city_id) && $building = Buildings::find_by_id($building_id)) {
      var_dump($city);
}

This returns: bool(true), and I expect result like the one before

Can someone explain to me what is happening?

War es hilfreich?

Lösung

What is happening here is that in first case you are just assigning function return value to variable $city

$city = Cities::find_by_id($city_id)

and result is pretty much what you would expected. For the second case you are doing something different - you are assigning

Cities::find_by_id($city_id) && $building = Buildings::find_by_id($building_id)

to variable $city which means if Cities::find_by_id and Buildings::find_by_id both return stdObjects there is logical and operator applied.

It is something like:

$city = (object) && (object)

which is pretty much same as

$city = true && true

You would probably want to do something like that (see extra parentheses):

if(($city = Cities::find_by_id($city_id)) && ($building = Buildings::find_by_id($building_id))) {
  var_dump($city);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top