plugin development – add_action() and call_user_func() to define and call a function outside a class
Hi Please see the following code of my class
class MyClass {
function __construct() {
$this->autoload_function();
}
function autoload_function(){
$my_array=array("test1");
foreach ( $my_array as $my_function ){
call_user_func($my_function);
}
}
function test1(){
echo 'hii- test1';
}
}
$var = new MyClass();
Here I have to add other values to $my_array and then I have to define other function outside this class . I have to do this via add_action. So I modified the code please see below
my-class.php
class MyClass {
function __construct() {
$this->autoload_function();
}
function autoload_function(){
$my_array=array("test1");
do_action('modify_array', $my_array);
foreach ( $my_array as $my_function ){
call_user_func($my_function);
}
}
function test1(){
echo 'hii- test1';
}
}
$var = new MyClass();
my-newpage.php
add_action ('modify_array', 'modify_array_function', 0);
function modify_array_function($my_array){
array_push($my_array, 'test2')
}
function test2(){
echo 'hii- test2';
}
Here i can see that new value is added to array but i am not sure about where i can write my new function i am getting following error
Warning: call_user_func() expects parameter 1 to be a valid callback,
class ‘MyClass’ does not have a method
‘test2’
I want to define test2() inside my-newpage.php and I am ready to add more action or filter inside my-class.php
I setup everything in a proper way that’s why add_action (‘modify_array’, ‘modify_array_function’, 0); is working .
Please help.
Leave an answer