如果条件,我可以在 PHP 中定义变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6741399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:07:47  来源:igfitidea点击:

Can I define a variable in a PHP if condition?

phpif-statement

提问by Casey

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.

如果函数没有返回任何内容,我想进入 else 语句。

回答by alex

Yes, that will work, and the pattern is used quite often.

是的,这行得通,而且这种模式经常使用。

If $my_arrayis assigned a truthyvalue, then the condition will be met.

如果$my_array被分配了一个值,那么条件将被满足。

CodePad.

键盘

<?php

function wp_get_category($id) {
   return 'I am truthy!';
}

if ($my_array = wp_get_category($id)) {
    echo $my_array;
} else {
    echo "1234";
}

The inverse is also true...

反之亦然...

If nothing is returned by the function, I want to go into the else statement.

如果函数没有返回任何内容,我想进入 else 语句。

A function that doesn't return anything will return NULL, which is falsey.

不返回任何内容的函数将返回NULL,这是falsey

CodePad.

键盘

<?php

function wp_get_category($id) {
}

if ($my_array = wp_get_category($id)) {
    echo $my_array;
} else {
    echo "1234";
}

回答by LainIwakura

you might want something like this:

你可能想要这样的东西:

if (!is_null($my_array = wp_get_category($id)) {
    echo "asdf";
else
    echo "1234";

Assuming the function returns null upon failure. You may have to adjust it a bit.

假设函数在失败时返回 null。您可能需要稍微调整一下。

回答by Explosion Pills

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

这实际上是一种常见的模式并且会起作用。但是,对于更复杂的情况,您可能要三思而后行,或者根本不考虑。想象一下,如果有人维护您的代码出现并看到

if ($x = one() || $y = two() && $z = three() or four()) {

}

It might be better to declare the variables before using them in the conditional.

在条件中使用变量之前先声明变量可能会更好。

回答by Teeks

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

http://codepad.org/xTwzTwGR

回答by jo0gbe4bstjb

Following is one more alternative to define any variable (with safety):

以下是定义任何变量的另一种选择(安全):

$my_array = ($my_array = $wp_get_category($id)) ?: /* else statement here */;