如何在IF语句中将字符串转换为条件

时间:2017-03-30 10:29:05

标签: php

假设我在$ condition变量中存储了一个字符串:

$condition = '2 == 2'; // returns TRUE

$condition = 'my_own_function()'; // which also returns TRUE

如何将它们转换为IF语句中的条件?说:

if (some_magic_converter_function($condition)){
    // execute something
}

就像我执行

一样
if (my_own_function()){
    // execute something
}

还有其他方法可以安全地将字符串评估为IF语句的条件吗?怎么样?

2 个答案:

答案 0 :(得分:1)

基本的经验法则:如果您需要使用eval(),那么您正在做一些非常错误的

但出于娱乐目的:

$condition = "return 2==2;";
$test = eval($condition);
if ($test) {
    echo 'Oh Noes';
}

function my_own_function()
{
    return true;
}
$condition = 'return my_own_function();';
$test = eval($condition);
if ($test) {
    echo "More Noes";
}

答案 1 :(得分:0)

我发现我们可以充分利用preg_match来完成上述任务:

/**
 * Function parse_condition
 * @param string $condition
 * @return bool
 */
function parse_condition($condition){
    // match {a} {condition} {b}
    preg_match('/.*(.*?)\s(.*?)\s(.*?)/sU', $condition, $condition_matches);

    // condition_matches[1] will be a, remove $, () and leading/tailing spaces
    $a = trim(str_replace(array('$','()'),'',$condition_matches[1]));

    // condition_matches[2] will be the operator
    $operator = $condition_matches[2];

    // condition_matches[3] will be b, remove $, () and leading/tailing spaces
    $b = trim(str_replace(array('$','()'),'',$condition_matches[3]));


    // It is advisable to pass variables into array or a "hive"
    // but in this example, let's just use global

    // Make variable's variable $$a accessible
    global $$a;
    // And for $$b too
    global $$b;

    $cmp1 = isset($$a)?($$a):($a);

    $cmp2 = isset($$b)?($$b):($b);

    switch($operator){
        case '==':
            return($cmp1 == $cmp2);
            break;
        case '!=':
            return($cmp1 != $cmp2);
            break;
        case '===':
            return($cmp1 === $cmp2);
            break;
        case '!==':
            return($cmp1 !== $cmp2);
            break;
        default:
            return false;
            break;
    }   
}

所以我可以像这样使用它:

// TESTCASES
$var_a = 100;
$var_b = 100;
$var_c = 110;
$var_d = (double) 100;


if(parse_condition('$var_a == $var_b')){ // TRUE
    echo 'Yeah I am Good!' . PHP_EOL;
}

if(parse_condition('$var_a != $var_c')){ // TRUE
    echo 'Good for this one too!' . PHP_EOL;
}

if(parse_condition('$var_b == $var_c')){ // FALSE
    echo 'Yeah I am Good!' . PHP_EOL;
}else{
    echo 'But I am not with this one :(' . PHP_EOL;
}

if(parse_condition('$var_a != 110')){ // TRUE
    echo 'I can compare values too' . PHP_EOL;
}

if(parse_condition('$var_a === $var_d')){ // FALSE
    //
}else{
    echo 'Or even tell the difference between data types' . PHP_EOL;
}