user1470443
user1470443

Reputation: 23

How to make a conditional statement out of a string

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!

Upvotes: 2

Views: 810

Answers (2)

geon
geon

Reputation: 8486

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.

Upvotes: 2

David Harkness
David Harkness

Reputation: 36562

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)) { ... }

Upvotes: 2

Related Questions