Can I store boolean comparison in a string?

I am trying to modulate a long lasting function if..else

.

$condition = "$a < $b";
if($condition)
{
    $c++;
}

      

Is there a way to translate a literal string into a boolean expression?

+3


source to share


4 answers


I am trying to make a modular long if..else function.

You don't need to put the condition on a string for this, just keep booleans true

or false

:

$condition = ($a < $b);
if($condition)
{
    $c++;
}

      

the values ​​of $ a and $ b can change between defining $ condition and using it



One solution would be closure (assuming the definition and use happens in the same scope):

$condition = function() use (&$a, &$b) {
    return $a < $b;
}
$a = 1;
$b = 2;
if ($condition()) {
    echo 'a is less than b';
}

      

But I don't know if this makes sense to you without remotely knowing what you are trying to accomplish.

+7


source


Use a lambda if you know the variables that are sufficient to determine the result



$f = function ($a, $b) { return $a < $b; }

if ($f($x, $y)){}

      

+2


source


you can do it using eval . not sure why you are not just evaluating this condition immediately.

+1


source


<?php
     $a=0;
     $b=1;
    function resultofcondition()
    {
        global $a,$b;
        return $a<$b;
    }
    if(resultofcondition()){
        echo " You are dumb,";
    }else{
        echo " I am dumb,"; 
    }
    $a=1;
    $b=0;
    if(resultofcondition()){
        echo " You were correct.";
    }else{
        echo " in your face.";
    }
?>

      

Indeed, thanks for commenting this out, the GLOBAL parameter was missing, for those who voted, what would this code output? Β¬_Β¬ w / e have fun xD

-4


source







All Articles