在if语句表达式中设置变量 [英] Set variable in if statement expression

查看:178
本文介绍了在if语句表达式中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天遇到了一些有趣的代码。我试图找出这是PHP的一个功能,还是我错过了什么,但无法在Google上找到任何内容。可能是因为我不知道它的名字。



代码

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

变量 $ logo 没有在其他任何地方设置。看来这个if语句中的表达式是检查该类方法是否返回任何内容并同时设置要在语句中使用的变量 $ logo 。 p>

这是真的吗?如果是这样,世界上有什么叫做!?

解决方案

你可以在有条件的情况下进行这样的任务。逻辑上发生的是,该值被分配给 $ logo 然后 $ logo 被评估是否是真实的。如果它是真实的,条件中的代码执行。



在循环数据库结果集的情况下,您经常会看到这种赋值/评估,但通常我为了清楚地阅读g代码,我们建议在这种常见用例之外避免使用它。


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!?!

解决方案

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.

这篇关于在if语句表达式中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆