PHP: assign function to class method
How do I assign a function to a method in a class in PHP? I tried the following:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar')
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName))
continue;
$this->{$functionName}() = function($params){ //should create the methods "foo" and "bar"
echo $variable; //should echo 'blablabla' (I know that the variable was declared outside this function, but how can I access it anyway?)
}; //the error points to here
}
}
}
But this code is giving me this error:
Fatal error: Can't use method return value in write context
Does anyone know how I can assign an anonymous function to a class method and also still have access to variables outside of that function?
source to share
You are executing foreach($functionNames as $functionName){
which means it $functionName
is a string, not an array. So don't use $functionName[0]
.
method_exists
takes 2 parameters. One is the object and the other is the method name. It should be:
method_exists($this, $functionName)
As for creating a function, you don't need ()
the left side =
. It should be:
$this->$functionName = function($params) use($variable){
echo $variable;
};
use($variable)
you need to tell PHP to use this variable inside a function. The way closures work in PHP is different from other languages.
So your class should look like this:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar');
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName)){
continue;
}
$this->$functionName = function($params) use($variable){
echo $variable;
};
}
}
}
The problem is that in this way of creating functions, you are not actually creating a class method, but instead creating a class variable that contains the function.
So, you need to call it like this:
$test = new Something;
$foo = $test->foo;
$foo('abc');
You cannot just do $test->foo('abc');
.
EDIT: Another thing you can do is use PHP's __call
"magic method". This will run whenever you do ->funcName()
, whether the method exists or not. Using this method, you can simply check if the method was called 'foo'
or 'bar'
. See this example:
class Something{
private $variable;
public function __construct(){
$this->variable = 'blablabla';
}
public function __call($name, $params=array()){
if(method_exists($this, $name)){
// This makes sure methods that *do* exist continue to work
return call_user_func(array($this, $name), $params);
}
else{
$functionNames = array('foo', 'bar');
if(in_array($name, $functionNames)){
// You called ->foo() or ->bar(), so do something
// If you'd like you can call another method in the class
echo $this->variable;
}
}
}
}
Now you can do the following:
$test = new Something;
$test->foo('abc'); // Will echo "blablabla"
source to share