tags:

views:

106

answers:

6

So I have something like the following:

$a = 3;
$b = 4;
$c = 5;
$d = 6;

and I run a comparison like

if($a>$b || $c>$d) { echo 'yes'; };

That all works just fine. Is it possible to use a variable in place of the operator? Something like:

$e = ||;

Which I could then use as

if($a>$b $e $c>$d) { echo 'yes'; };
A: 

Nope, there is no way to re-define operators (or use variable operators) in PHP AFAIK.

Short of using eval(), the closest I can think of is creating a function:

function my_operator ($cond1, $cond2)
 {
   if ( ....  ) 
     return ($cond1 || $cond2);
   else
     return ($cond1 && $cond2);

 }

if (my_operator(($a > $b), ($c > $d)))
 ....
Pekka
+2  A: 

No, it is not possible.

Anthony Forloney
+5  A: 

No, that syntax isn't available. The best you could do would be an eval(), which would not be recommended, especially if the $e came from user input (ie, a form), or a switch statement with each operator as a case

switch($e)
{
    case "||":
        if($a>$b || $c>$d)
            echo 'yes';
    break;
}
Kristopher
+1  A: 

nope. there is no way to do this in php.

zerkms
A: 

You could use eval, but that you could easily end up exposing your site to all sorts of code injection attacks if you're not very careful.

A safer solution would be to match the proposed operator against a predefined white list and then call a corresponding bit if code with the operator hard - coded.

C.

symcbean
+1  A: 

It's not possible, but you could use a function instead. Of course, you'd have to define them yourself. This would be fairly simple using PHP 5.3's closures:

$or = function($x, $y)
{
    return $x || $y;
};

if ($or($a > $b, $c > $d))
{
    echo 'yes';
};
Will Vousden
+1. Closures FTW.
outis