Is it possible to use object in add_action?

So is it possible to do something like this with add_action?

class class{}
$my_class = new class;
add_action('init', 'my_class');

Related posts

Leave a Reply

3 comments

  1. You can do this:

    class testclass {
      function test() {
        echo 'howdy';
      }
    }
    add_action('wp_head',array('testclass','test'));
    

    Or this:

    $t = new testclass();
    add_action('wp_head',array($t,'test'));
    

    It doesn’t work like…

    $t = new testclass();
    add_action('wp_head','t');
    // or this either, for good measure
    $t = new testclass();
    add_action('wp_head',array('t'));
    

    .. but I am not sure what you are trying to accomplish by using that pattern. You’ve already instantiated the class so the constructor, if present, has already ran. Without a callback method, I don’t know what you expect to happen.

  2. In the (accepted) answer the first example is incorrect:

    class testclass() {                             
        function test() {                             
            echo 'howdy';                               
        }                                             
    }                                               
    add_action( 'wp_head', array( 'testclass', 'test' ) );
    

    It is incorrect because method test is not static.

    The correct use for the static call in the action would be:

    class testclass() {                             
        function static test() {                             
            echo 'howdy';                               
        }                                             
    }                                               
    add_action( 'wp_head', array( 'testclass', 'test' ) );
    

    you could also write it then as:

    add_action( 'wp_head', 'testclass::test' );