我可以在PHP if条件中定义变量吗? [英] Can I define a variable in a PHP if condition?

查看:148
本文介绍了我可以在PHP if条件中定义变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我可以这样做:

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

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

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

推荐答案

是的,这样可行,并且经常使用该模式。

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

如果 $ my_array 分配了 truthy 值,则会满足条件。

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


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

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

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

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";
}

这篇关于我可以在PHP if条件中定义变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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