Class or function wrapper for plugin code

Are the above practices both valid?

I’ve never seen anyone use method B. Functions declared inside functions still need to be unique. Therefore, just because they are declared inside another function does not guarantee that there won’t be a name conflict. As far as I can tell, there is no useful purpose in doing this.

Is using a class inherently better?

Yes. Using a class is better. Then you can name the methods whatever you want in the class. Better yet, use namespaces. Then you can use classes as they were intended instead of as pseudo-namespaces.

There is something I don’t get about case B: how does the hook get the scope of the target function if you only pass it the string name?

You don’t just pass the string. You pass an array:

Static method: [ 'MyClass', 'MyMethod' ]

Non-static method: [ new MyClass(), 'MyMethod' ]

If you use namespaces (as you should), it would be:

Static method: [ '\MyNamespace\MyClass', 'MyMethod' ]

Non-static method: [ new \MyNamespace\MyClass(), 'MyMethod' ]


As an example, suppose we have a file named class-stackexchange-example.php that contains a class called example in the StackExchange namespace as so:

<?php
namespace StackExchange;

class example {
  public function register() {
    //* Do something awesome
  }
}

Now suppose that our main plugin file ( stackexchange-example.php ) wants to hook into the register method on the admin_init hook. To do that we’d add the following to our stackexchange-example.php file:

add_action( 'admin_init', [ new \StackExchange\sample(), 'register' ] );

Assuming you include the required PHP file correctly, this will now call the register method of the sample class in the StackExchange namespace on the admin_init hook.

Namespaces were introduced in PHP 5.3. Unless you have a need to support 5.2, I’d encourage you to use them in new projects.