Alfo
Alfo

Reputation: 4819

PHP Take a Variable in an If statement literally

I was wondering if it would be possible to do this:

$var = '$something == $somethingelse';

if ($var) { // Say hello }

and have it mean the same thing as this:

if ($something == $somethingelse) { // Say hello }

I know this will not work at the moment, because if ($var) checks to see if $var is set or not. But what I'm asking is: is there a method to allow this? Would appreciate an answer.

EDIT: Basically I feel I should explain why I am doing this. I want users to be able to control when they get a notification, based off some data that one of their "channels" has saved.

For instance, a user only wants to get a notification when their collected data is bigger than 60. So I would get them to choose two fields:

First field input of their number (int or float)

Second field choises (equals, <, >, =<, =>)

The last thing in this if statement would be their data collected by their "channel".

I then want to be able to save their choice in a database, somehow, and then later act upon their choices.

Upvotes: 0

Views: 128

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157918

If you come to this question, then there is something wrong with your design.

Mixing the code with data (what are you actually doing) is one of worst things a programmer can do. It will make your code unmaintainable and insecure.

You have to redesign your application to make your code solid and not variable.

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227290

You say this string is being generated by you elsewhere. I suggest, instead of generating a string, generate an array.

Like this: array('something','==','somethingelse').

Now when you want to process this, you can replace the variables with their values, and then check the operator and run the correct operation.

Something like this:

$x = array('something','==','somethingelse');
list($valA, $operation, $valB) = $x;

// Replace values
$valA = $$valA;
$valB = $$valB;

// Run operation
$result = false;
switch($operation){
    case '==':
        $result = $valA == $valB;
        break;
    default:
        break;
}
if($result) echo ":-)";

DEMO: http://codepad.org/vaELABEm

You can even use this to do other things, by adding more cases to the switch.

Upvotes: -1

Why not just use if ($something == $somethingelse) { // Say hello }? It's not that much more code.

Upvotes: 0

David Chan
David Chan

Reputation: 7505

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Upvotes: 4

Related Questions