php - Assigning a function to a property of a class
I'm trying to do something similar to PHP anonymous function assigned to class property in constructor is always null?, but my solution seems more simple. I wanted comments from the Stack Overflow Hot Shots on this solution and whether there is a better one. This is kind of a 'best practices' question.
I want to pass a function (anonymous or defined) to a class/object and be able to call that function later. I started with this :
function Foo($arg) {return sprintf('In Foo(%s)',$arg);}
function Bar($arg) {return sprintf('In Bar(%s)',$arg);}
class TestIt {
private $func;
public function __construct( $func ) { $this->func = $func; }
public function OutPut($arg) {
return $this->func($arg);
}
}
$test = new TestIt('Foo');
echo $test->OutPut('Bozo');
When this is run, I get an error that the method$this->func
doesn't exist. If I put ais_callable
test inside the methodOutPut()
, I find the$this->func
is, in fact, callable, but the error persists.
However, if I us the third argument ofis_callable
, I get this to work fine.
public function OutPut($arg) {
return is_callable($this->func,false,$tmpfunc) ? $tmpfunc($arg) : null;
}
How does this stack up as a solution? Curious of your thoughts.
Answer
Solution:
Because there is no way to get PHP to parse
$this->func()
as a variable function, you have two options here:Or:
is_callable()
will return a static method callsomeClass::someMethod
even if it is not a static method and is called in object scope.