admin管理员组

文章数量:1317898

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.

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.

Share Improve this question asked Oct 27, 2020 at 4:10 Jhonatan VillenaJhonatan Villena 1012 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

本文标签: pluginsWhy do actions with class and public method don39t fire construct()