简体   繁体   中英

Operator as a Variable in PHP

Im trying to compute a simple expression in PHP, the expression will always be the same the only change is in the operator.

Is there a simple solution to rather than duplicate the formula, just use the single expression and have the operator as a variable.

Something like..

function calc($qty, $qty_price, $max_qty, $operator_value, $operator = '-') 
{

  $operators = array(
   '+' => '+',
   '-' => '-',
   '*' => '*',
  );

  //adjust the qty if max is too large
  $fmq = ($max_qty > $qty)? $qty  : $max_qty ;


  return ( ($qty_price  . $operators[$operator] . $operator_value) * $fmq ) + ($qty - $fmq) * $qty_price;

}

If youre using 5.3+ then just use functions as your operator values:

$operators = array(
   '+' => function (a,b) { return a+b; },
   '-' => function (a,b) { return a-b; },
   '*' => function (a,b) { return a*b; },
);

$fmq = ($max_qty > $qty)? $qty  : $max_qty ;


return ( $operators[$operator]($qty_price, $operator_value) * $fmq ) + ($qty - $fmq) * $qty_price;

If youre using < 5.3 then you can use create_function() to do much the same.

The 5.3 answer is nice, however, why not pre-calcaute $qty_price +-* $operator_value rather than repeating the whole function? It'd make the code a little more readable...

Eg

function calc($qty, $qty_price, $max_qty, $operator_value, $operator = '-') 
{
  $qty_price_orig = $qty_price;

  switch($operator) {
      case '-':
         $qty_price -= $operator_value;
         break;
      case '+':
        $qty_price += $operator_value; 
        break;
      case '*':
         $qty_price = $qty_price * $operator_value; 
         break;


  //adjust the qty  i max is too large
  $fmq = ($max_qty > $qty)? $qty  : $max_qty ;


  return ( $qty_price * $fmq ) + ($qty - $fmq) * $qty_price_orig;

}

If you want to use eval() to get the job done:

<?php
$operators = array(
   '+' => '+',
   '-' => '-',
   '*' => '*',
  );

$a = 3;
$b = 4;
foreach ($operators as $op) {
    $expr = "$a ".$op." $b";
    eval("\$result=".$expr.";");
    print_r($expr." = ".$result."\n");
}
?>

However, use it with caution! Here is the official warning:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM