0

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_filter. 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");

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

my-newpage.php

add_filter ('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_filter ('modify_array', 'modify_array_function', 0); is working .

Please help.

3
  • 1
    If you want to modify a value then you should be using apply_filters, not add_action: $my_array = apply_filters( 'modify_array', $my_array );. This isn't the cause of your problem though. Dec 31 '21 at 7:09
  • @JacobPeattie thank you for the suggestion. You are right, modified it . Dec 31 '21 at 8:01
  • actually i mad it using add_action because i think that i can define the function inside add action function ie function modify_array_function($my_array){ funtion test2(){ echo 'hii- test2'; } array_push($my_array, 'test2') } but that also not working Dec 31 '21 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.