2

Is this possible at all? The idea is to have the following:

if ($some_statement) { ... } 

where $some_statement variable is a string, which looks like this:

$some_statement = ' $day == "Monday" && $weather == "sunny" '; 

I have experimented a little with curly brackets and eval function, but could not get any to work. Thanks guys, you rock!

3
  • 2
    Where does the string come from, is it user input? Is it trusted user input? Commented Jun 20, 2012 at 20:58
  • many probably find it easier to write if( $day == "Monday" && $weather == "sunny" ) Commented Jun 20, 2012 at 21:00
  • yes, user input should not be evaluated. Unless grate care is taken. Commented Jun 20, 2012 at 21:03

2 Answers 2

2

You can use eval for this, but keep in mind that the statement in the string must be a complete PHP statement.

$condition = 'return $day == "Monday" || $day == "Sunday";'; if (eval($condition)) { ... } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I think this would not work without "return" and ";" at the end of a string!
2
If (eval($some_statement)) { 

should work.

But don't do it unless you know what you are doing, which judging by your question you don't.

Evaluating code in a string is very dangerous, and can very easily create serious security holes.

1 Comment

Thank you very much, and yes, you are right - I have no idea what I am doing :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.