By passing a reference to a function as an argument
How can I pass a function reference to another function as an argument? I was trying to do a callback and I need to pass the reference to the function returnProduct
before. How to do it?
<?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);
+3
source to share
2 answers
If you only wanted to use a method Tester
, you can pass the method name as a string, for example
public function calculate($var_1, $var_2, $var_3) {
$product = $this->$var_3($var_1, $var_2);
echo $product;
}
Then call it
$obj->calculate(100, 2, 'returnProduct');
To err on the side of caution, you can check if a method exists using the aptly named method_exists()
+1
source to share