我可以在 PHP if 条件中定义变量吗?
例如,我可以这样做:
if ($my_array = wp_get_category($id)) {
echo "asdf";
} else {
echo "1234";
}
如果函数没有返回任何内容,我想进入 else 语句。
For example, can I do:
if ($my_array = wp_get_category($id)) {
echo "asdf";
} else {
echo "1234";
}
If nothing is returned by the function, I want to go into the else statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我总是觉得这个原则令人困惑,因为它似乎对我不起作用!采用以下代码:
if ($pid = $arr['Key']){
这可能会引发错误
Undefined index: Key
。同样,我得到了相同的结果:if (!empty($pid = $arr['Key']))
现在 PHP7+ 的解决方案如下:
if ($pid = $arr['Key'] ?? false)
这将允许数组具有空值设置
$pid = false;
并且不触发 IF 语句。我希望这对某人有所帮助,因为数组让我感到困惑,但双合并非常有用,可以在
if
概念中使用。I always found this principle confusing as it never seemed to work for me! Take the following code:
if ($pid = $arr['Key']){
This may throw an error
Undefined index: Key
. Equally I get the same result with this:if (!empty($pid = $arr['Key']))
The solution now with PHP7+ is as follows:
if ($pid = $arr['Key'] ?? false)
Which will allow for an array with an empty value setting
$pid = false;
and not triggering the IF statement.I hope that helps someone as arrays threw me but the double coalesc is super helpful and can be used in the
if
concept.是的,这会起作用,并且该模式经常被使用。
如果为
$my_array
分配了一个 truthy 值,则满足条件。CodePad。
反之亦然...
不返回任何内容的函数将返回
NULL
,即 falsey。CodePad。
Yes, that will work, and the pattern is used quite often.
If
$my_array
is assigned a truthy value, then the condition will be met.CodePad.
The inverse is also true...
A function that doesn't return anything will return
NULL
, which is falsey.CodePad.
这实际上是一种常见的模式并且会起作用。但是,您可能需要三思而后行才能将其用于更复杂的情况,或者根本不使用它。想象一下,如果有人维护您的代码,并看到
在条件中使用变量之前声明变量可能会更好。
This is in fact a common pattern and will work. However, you may want to think twice about using it for more complex cases, or at all. Imagine if someone maintaining your code comes along and sees
It might be better to declare the variables before using them in the conditional.
continue
I found this wondering about the rules of declaring a variable then using it immediately in subsequent conditions in the same statement.
Thanks to previous answer for the codepad link, I made my own to test the theory.
Spoiler alert: It works.
http://codepad.org/xTwzTwGR
你可能想要这样的东西:
假设函数在失败时返回 null。您可能需要稍微调整一下。
you might want something like this:
Assuming the function returns null upon failure. You may have to adjust it a bit.
以下是定义任何变量的另一种选择(安全):
Following is one more alternative to define any variable (with safety):