Class MyClass{
private $data=array['action'=>'insert'];
public function insert[]{
echo 'called insert';
}
public function run[]{
$this->$this->data['action'][];
}
}
This doesn't work:
$this->$this->data['action'][];
Is the only possibility to use call_user_func[];
?
Melebius
5,8504 gold badges35 silver badges49 bronze badges
asked Mar 27, 2011 at 18:37
Try:
$this->{$this->data['action']}[];
You can do it safely by checking if it is callable first:
$action = $this->data['action'];
if[is_callable[array[$this, $action]]]{
$this->$action[];
}else{
$this->default[]; //or some kind of error message
}
answered Mar 27, 2011 at 18:38
Mārtiņš BriedisMārtiņš Briedis
17.1k5 gold badges53 silver badges74 bronze badges
5
Reemphasizing what the OP mentioned, call_user_func[]
and
call_user_func_array[]
are also good options. In particular, call_user_func_array[]
does a better job at passing parameters when the list of parameters might be different for each function.
call_user_func_array[
array[$this, $this->data['action']],
$params
];
answered Oct 8, 2012 at 16:27
Brad KochBrad Koch
18.3k18 gold badges107 silver badges135 bronze badges
Created: February-23, 2022 PHP has a built-in function like This tutorial demonstrates different methods to call a function from a string stored in a variable. PHP built-in function Example: The code above calls the function Output: In PHP, we can also store the functions in variables. The function name should be assigned to a variable as a string, and
then we can call the function a variable. Example: The output for this will also be similar to our first example above.call_user_func[]
Call a Function From a String in PHPcall_user_func[]
to call a function from a string or store it in a variable for the older versions. PHP can also store a function into a variable and use it wherever required.Use
call_user_func[]
Call a Function From a String in
PHPcall_user_func[]
can be used for the purpose.
demo_func
with the parameter name.Hello This is Delftstack employee John
Hello This is Delftstack employee Shawn
Hello This is Delftstack employee Michelle
Hello This is Delftstack employee Tina
Use the Variable Method to Call a Function From a String Stored in a Variable in PHP
Hello This is Delftstack employee John
Hello This is Delftstack employee Shawn
Hello This is Delftstack employee Michelle
Hello This is Delftstack employee Tina
call_user_func
is the old way to do it. We can directly store the function into variables as a string and call the function by calling the variable.Related Article - PHP Function