简体   繁体   中英

php - passing an operator to a function

Is it possible to pass an operator to a function? Like this:

function operation($a, $b, $operator = +) {
    return $a ($operator) $b;
}

I know I could do this by passing $operator as a string and use switch { case '+':... } . But I was just curious.

It's not possible to overload operators in php, but there is a workaround. You could eg pass the functions add, sub, mul and etc.

function add($a, $b) { return $a+$b; }
function sub($a, $b) { return $a-$b; }
function mul($a, $b) { return $a*$b; }

And then you function would be something like:

function operation($a, $b, $operator = add) {
    return $operator($a, $b);
}

This can be done using eval function as

function calculate($a,$b,$operator)
{

    eval("echo $a $operator $b ;");
}

calculate(5,6,"*");

Thanks.

Try, You cannot able to pass the operators in functions, YOU CAN USE FUNCTION NAME LIKE ADDITION, SUBTRACTION, MULTIPLICATION ... etc,

function operation($a, $b, $operator ='ADDITION') {

     $operator($a, $b);
}

 function ADDITION($a, $b){
       return $a + $b;
 }

I know you specifically mention not using a switch statement here, but I think it's important to show how this could be set up using switch statements as in my opinion it is the easiest, safest, and most convenient way to do this.

function calculate($a, $b, $operator) {
    switch($operator) {
        case "+":
            return $a+$b;
        case "-":
            return $a-$b;
        case "*":
            return $a*$b;
        case "/":
            return $a/$b;
        default:
            //handle unrecognized operators
    }
    return false;
}

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