0

I'm trying to understand how WordPress works with actions, classes, and methods.

If there is a class "TestClass" and it has a public method 'method1'

The method can be hooked to any action as "add_action('theHook', ['TestClass', 'method1']);"

From my understanding. If you don't initialize the class, you can not access its public methods and objects. Now, I would assume that WordPress has to follow this, and it must initialize my "TestClass", which will cause for public __construct() to fire.

However, after testing this, it does not fire __construct()..

Why is this?. I know a fix would be to self initialize inside 'method1', but I'm trying to figure out why WordPress behaves this way.

1 Answer 1

0

In these cases the methods are called statically. The class might look like this, note the static keyword:

class Foo 
{
    public static function bar()
    {
        echo "Hello, world!";
    }
}

And then you can register the callback like this:

add_action( 'hookname', ['Foo', 'bar'] );

There is no object instance, so no __construct() will be called. This is basically just a way to "name space" procedural functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.