admin管理员组

文章数量:1122832

I am currently learning how to create WordPress plugins using my basic knowledge of OOP and am a bit stumped on how I can use a class from one plugin inside another. Both of my plugins have unique namespaces and the classes are being autoloaded with Composer.

I have attempted to insert the "use" keyword to import the specific namespace class but am unable to call the static functions inside of it directly.

//Plugin 1
namespace Test\PluginName1;
class Function {
   public static function example() {
       echo "test";
   }
}

//Plugin 2
namespace Test\PluginName2;
use Test\PluginName1\Function;

class Test {
    public static function frontend_output() {
        $message = Function::example();
    }
}

What would be the best way to include a class from another namespace?

Sorry if this seems simple but I can't work this one out.

Thank you.

I am currently learning how to create WordPress plugins using my basic knowledge of OOP and am a bit stumped on how I can use a class from one plugin inside another. Both of my plugins have unique namespaces and the classes are being autoloaded with Composer.

I have attempted to insert the "use" keyword to import the specific namespace class but am unable to call the static functions inside of it directly.

//Plugin 1
namespace Test\PluginName1;
class Function {
   public static function example() {
       echo "test";
   }
}

//Plugin 2
namespace Test\PluginName2;
use Test\PluginName1\Function;

class Test {
    public static function frontend_output() {
        $message = Function::example();
    }
}

What would be the best way to include a class from another namespace?

Sorry if this seems simple but I can't work this one out.

Thank you.

Share Improve this question asked May 23, 2024 at 14:30 SimonSimon 1
Add a comment  | 

1 Answer 1

Reset to default 0

Its likely due to the WordPress load process. Plugins are not all loaded at once. It's possible that when you in the constructor phase on one plugin the other plugin is not yet loaded.

This means you need to "hook" into the "init" of WordPress and check your function or class exists before running your class constructor.

Ways to deal with this:

  1. Use an init hook and registration to make sure the class exists before your dependant function is loaded.

  2. Update your Autoloader inside the dependant plugin to use the PSR-4 or what ever autoloader you are using to get the class so you know it will exist.

  3. Directly require the file inside your plugin init that has the child class.

  4. Convert you classes to a composer package so you can load it and namespace it in each plugin.

All are a bit messy but plugins are meant to be isolated. Look up pluggable functions and it should give you an idea of some next steps.

本文标签: Is it possible to use Classes between WordPress plugins with separate namespaces