Php逻辑表达式和对象

时间:2014-05-11 21:12:43

标签: php object logic

这对我来说很奇怪。

代码1:

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

返回:object(Cities)#6(7){...},普通

代码2:

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

返回:bool(true),我希望结果与之前的结果相同

有人可以向我解释发生了什么吗?

1 个答案:

答案 0 :(得分:1)

这里发生的事情是,在第一种情况下,您只是将函数返回值赋给变量$ city

$city = Cities::find_by_id($city_id)

结果几乎是你所期望的。对于第二种情况,您正在做一些不同的事情 - 您正在分配

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

到变量$ city,这意味着如果Cities :: find_by_id和Buildings :: find_by_id都返回stdObjects,则应用逻辑运算符。

类似于:

$city = (object) && (object)

几乎相同
$city = true && true

您可能想要做类似的事情(参见额外的括号):

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