Site icon Hip-Hop Website Design and Development

Define a function outside a class and call the function using action or filter hook

Hi Currently i am developing a sub plugin for my own main plugin. Please see the main plugin code below

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();

My sub plugin need to add more values to $my_array and i am allowed to use do_action or apply_filtere in main plugin.

I added apply_filters, so that i can modify the $my_array in my sub plugin.

my-class.php

class MyClass {
     function __construct() {
        $this->autoload_function();
     }
     
     function autoload_function(){
        $my_array=array("test1");

        apply_filters('modify_array', $my_array);

        foreach ( $my_array as $my_function ){
         call_user_func($my_function);
        }
     }
     
     function test1(){
        echo 'hii- test1';
     }
}

$var = new MyClass();

In my sub plugin i checked the filter and i can see that filter is working perfectly so that i can modify the value of $my_array in my sub plugin.

my-newpage.php

add_filter ('modify_array', 'modify_array_function', 0);


function modify_array_function($my_array){
 array_push($my_array, 'test2')
}

Here i can see that new value is added to array but now i have to define test2 function inside my sub plugin .

function test2(){
 echo 'hii- test2';
}

When i write test2 function in my sub plugin i am getting below error .

Warning: call_user_func() expects parameter 1 to be a valid callback,
class ‘MyClass’ does not have a method
‘test2’

Now how can i solve this ? Do i need to add more action or filters in the sub plugin .

The issue is due to call_user_func('test2'); is called inside my-class.php but the test2 function is defined outside mycalss. It is defined inside my sub plugin.

Please help to solve this error.