PHP allows variables to hold functions like this:
$f = function($a,$b) { print "$a $b"; }; $f("Hello","World!"); //prints 'Hello World!'
This works great for me. I am trying to pass a function to a class and set an instance variable to store this function, but with little luck:
class Clusterer { private $distanceFunc; public function __construct($f) { $this->distanceFunc = $f; print $f(1,7); //works print $this->distanceFunc(1,7); //exceptions and errors abound } } $func = function($a,$b) { return abs($a-$b); } $c = new Clusterer($func);
Am I doing something wrong here? The error is that the function does not exist, so I am currently assuming that it is looking for a class function with this name (which does not exist), and then refuses, and not looking for variables ... how can I get it to look at $ this -> distanceFunc as a variable?
EDIT: So, after the recommendations from the answers below, I found a solution that was a function to wrap the call. For example, my class is now:
class Clusterer { private $distanceFunc; public function __construct($f) { $this->distanceFunc = $f; print $f(1,7); //works print $this->distanceFunc(1,7); //exceptions and errors abound } private function distanceFunc($a,$b) { $holder = $this->distanceFunc; return $holder($a,$b); } } $func = function($a,$b) { return abs($a-$b); } $c = new Clusterer($func);
and it works great. Php is looking for functions first and can only say if it is a variable in context, I think this is the moral of the story.
php class instance-variables function-pointers
hackartist
source share