Reputation: 2497
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.
Upvotes: 0
Views: 1907
Reputation: 8621
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;
}
Upvotes: 0
Reputation: 3165
This can be done using eval function as
function calculate($a,$b,$operator)
{
eval("echo $a $operator $b ;");
}
calculate(5,6,"*");
Thanks.
Upvotes: 2
Reputation: 22721
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;
}
Upvotes: 1
Reputation: 377
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);
}
Upvotes: 6