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

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

问题描述

例如,我可以这样做:

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

反之亦然...

如果函数没有返回任何内容,我想进入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 中定义一个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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