3

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

Is it possible to use the value of a string in the expression of an if statement? For example, say I pass

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

to a function and call it $string, could I then use that value as the conditional evaluation of an if statement?

if (the value of $string) {}

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

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

1
  • Warnings about using eval aside, it is probably returning NULL because you have an error in your string. Does eval('strcasecmp("hello", "Hello") == 0'); return the 'right' answer? Commented Mar 6, 2012 at 17:09

3 Answers 3

6

I must guess a bit, maybe you want to return from eval?

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

Also, there are closures that might add a bit more fluidity:

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

$string = 'strcasecmp("hello", "Hello") == 0';
if ($if($string)) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

The if statement does not return anything, so your example won't work. However, you can store the expression as a string and eval it later:

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

Now, keep in mind that using eval is extremely discouraged, as it can lead to serious security problems.

Comments

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

Though what you're trying to do is very bad.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.