将IF条件放入变量中 [英] Put IF condition inside a variable

查看:87
本文介绍了将IF条件放入变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将条件放入变量,然后在if语句中使用该变量?参见下面的示例:

Is there any way to put conditions within a variable and then use that variable in an if statement? See the example below:

$value1 = 10;
$value2 = 10;

$value_condition = '($value1 == $value2)';

if ($value_condition) {
    echo 'It works!';
} else {
    echo 'It doesnt work.';
}

我知道这可能是一个奇怪的问题。我正在学习PHP的基础知识。

I understand this may be a bizarre question. I am learning the basics of PHP.

推荐答案

无需使用字符串。直接以这种方式使用它:

No need to use strings. Use it directly this way:

$value1 = 10;
$value2 = 10;

$value_condition = ($value1 == $value2);

if ($value_condition) {
    echo 'It works!';
} else {
    echo 'It doesnt work.';
}

或者要进行评估,可以使用 ,因为它在 {...} 内扩展并求值。

Or to evaluate, you can use this way using ", as it expands and evaluates variables inside { ... }.

我认为这可能行得通!而且,使用 eval()是邪恶的!因此,请确保在正确的位置使用它,以确保没有其他输入 eval()函数!

I reckon it might work! Also, using eval() is evil! So make sure you use it in right place, where you are sure that there cannot be any other input to the eval() function!

这篇关于将IF条件放入变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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