最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

php - How to pass argument to add_action while the method is inside a class?

matteradmin8PV0评论

in my functions.php I have

require 'autoloader.php';
add_action('init', 'MyClass::make');

and in my MyClass class I have

class MyClass {
    public static function make($type) {
        var_dump($type);die;
    }
}

but the output of var_dump is string(0) "". What I want is to pass the argument to this class as $type. What I tried was to pass it through do_action however I think it is not best practice.

How can I pass argument to a method which is inside a class for add_action?

in my functions.php I have

require 'autoloader.php';
add_action('init', 'MyClass::make');

and in my MyClass class I have

class MyClass {
    public static function make($type) {
        var_dump($type);die;
    }
}

but the output of var_dump is string(0) "". What I want is to pass the argument to this class as $type. What I tried was to pass it through do_action however I think it is not best practice.

How can I pass argument to a method which is inside a class for add_action?

Share Improve this question edited Apr 2, 2019 at 5:32 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Apr 1, 2019 at 21:03 AlexAlex 1
Add a comment  | 

2 Answers 2

Reset to default 1

Here's another example on how you could implement the add_action:

$type = 'my_sample_type';

add_action(
    'init',
    function() use ( $type ) {
        MyClass::make( $type );
    }
);

The init hook doesn't pass any parameters - when you call add_action, init isn't passing anything to make.

You could just call make outright:

require 'autoloader.php';
MyClass::make( <whatever );

If you need to do this on init, set up a callback function:


function add_my_type() {
    MyClass::make( <foo> );
}

add_action( 'init', 'add_my_type' );
Post a comment

comment list (0)

  1. No comments so far