Reputation: 21329
How can I pass the reference of a function to another function as an argument ? I was trying to implement a callback and I need to pass the reference of the function returnProduct
before.How do I do that ?
<?php
class Tester {
public function calculate($var_1,$var_2,$var_3) {
$product = var_3($var_1,$var_2);
echo $product;
}
public function returnProduct($var_1,$var_2) {
return $var_1*$var_2;
}
}
$obj = new Tester();
$obj->calculate(100,2,$obj->returnProduct);
Upvotes: 3
Views: 63
Reputation: 164742
If you only wanted to use a method of Tester
, you can pass the method name as a string, eg
public function calculate($var_1, $var_2, $var_3) {
$product = $this->$var_3($var_1, $var_2);
echo $product;
}
Then call it with
$obj->calculate(100, 2, 'returnProduct');
To err on the side of caution, you can check if the method exists using the aptly named method_exists()
Upvotes: 1
Reputation: 324620
Change your $product =
line to:
$product = call_user_func($var_3,$var_1,$var_2);
And change your calling line to:
$obj->calculate(100,2,array($obj,'returnProduct'));
Upvotes: 3