Best way to initiate a class in a WP plugin?
-
04-11-2019 - |
質問
I've created a plugin, and of course being me, I wanted to go with a nice OO approach. Now what I've been doing is to create this class and then just below create an instance of this class:
class ClassName {
public function __construct(){
}
}
$class_instance = new ClassName();
I'm assuming there is a more WP way to have this class initiated, and then I came across people saying that they prefer to have an init()
function than a __construct()
one. And similarly I found the a few people using following hook:
class ClassName {
public function init(){
}
}
add_action( 'load-plugins.php', array( 'ClassName', 'init' ) );
What is generally considered the best way to create a WP class instance on load and have this as a globally accessibly variable?
NOTE: As an interesting side point, I've noticed that while register_activation_hook()
can be called from within the __construct
, it cannot be called from within the init()
using the second example. Perhaps someone could enlighten me on this point.
Edit: Thanks for all the answers, there clearly is a fair bit of debate as to how handle the initialization within the class itself, but I think there's generally a pretty good consensus that add_action( 'plugins_loaded', ...);
is the best way to actually kick it off...
Edit: Just to confuse matters, I've also seen this used (although I wouldn't use this method myself because turning a nicely OO class into a function seems to defeat the point of it):
// Start up this plugin
add_action( 'init', 'ClassName' );
function ClassName() {
global $class_name;
$class_name = new ClassName();
}
正しい解決策はありません