Can I define a variable in a PHP if condition?

早过忘川 提交于 2019-12-28 05:58:00

问题


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.


回答1:


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.

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

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

CodePad.

<?php

function wp_get_category($id) {
}

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



回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/6741399/can-i-define-a-variable-in-a-php-if-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!