Use string value as if else statement

This is probably the dumbest question, and the answer is probably NO, but ...

Can a string value be used in an if statement? For example, let's say I pass

'if strcasecmp("hello", "Hello") == 0'

      

for a function and call it $ string, can I use this value as a conditional evaluation of the if statement?

if (the value of $string) {}

      

I know that eval () will execute the string as if it were PHP code, but it actually executes it and returns null / false, rather than just letting PHP surrounding the string process the contents of the string. I also know that you can use variable variables with $ {$ varname} which will tell php to use $ varname as the variable name.

So, I guess what I'm looking for is something like "variable code" instead of "variable variables".

+3


source to share


3 answers


I have to guess a little, maybe you want return

from eval

?

 if (eval('return strcasecmp("hello", "Hello") == 0;')) {}

      



In addition, there are closures that can add a little more fluidity:

$if = function($string) {
    return eval(sprintf('return (%s);', $string));
}

$string = 'strcasecmp("hello", "Hello") == 0';
if ($if($string)) {
    ...
}

      

+6


source


The operator if

doesn't return anything, so your example won't work. However, you can save the expression as a string, and more on that later:

$expr = 'strcasecmp("hello", "Hello") == 0';
$val = eval($expr);

      



Now, keep in mind that usage is eval

highly discouraged as it can lead to serious security issues.

+1


source


if( eval("return ({$string});") ):
...
endif;

      

Although what you are trying to do is very bad.

0


source







All Articles