0

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.

1

4 Answers 4

6

It's not possible to overload operators in php, but there is a workaround. You could e.g. 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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes. This is interesting. But I don't see much a difference between this and switch case method.
Well, in a sense there is not much difference between any method that works. However, I would argue that the presented code would be cleaner than any method based on string operations or a switch case method. Please, post your switch case method. It would be interesting to compare.
I got my answer. I was looking for "It's not possible to overload operators". Alternative solutions are different issues. But it would be cool if we could overload operators, as C# does. Assume you want to operate on complex numbers or any other custom classes.
2

This can be done using eval function as

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

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

calculate(5,6,"*");

Thanks.

Comments

1

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;
 }

1 Comment

He specifically said he knows you can use a switch, he was interested if there's a different way.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.