I am trying to modularise a lengthy if..else
function.
$condition = "$a < $b";
if($condition)
{
$c++;
}
Is there any way of translating the literal string into a logical expression?
I am trying to modularise a lengthy if..else
function.
$condition = "$a < $b";
if($condition)
{
$c++;
}
Is there any way of translating the literal string into a logical expression?
I am trying to modularise a lengthy if..else function.
You don't need to put the condition in a string for that, just store the boolean true
or false
:
$condition = ($a < $b);
if($condition)
{
$c++;
}
the values of $a and $b may change between definition of $condition and its usage
One solution would be a Closure (assuming that definition and usage are happening 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 for you without remotely knowing what you are trying to accomplish.
Use lambda if you know variables that are enough to determine result
$f = function ($a, $b) { return $a < $b; }
if ($f($x, $y)){}
you could do this using eval. not sure why you wouldn't just evaluate the condition immediately, though.
<?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 that out, was missing the GLOBAL parameter, for those who voted down, what would that code output? ¬_¬ w/e have fun xD