Instantiating objects

Posted 11 months ago by lievikoff

I am confused with instantiating object in PHP.

I have this files:

  • Index.php (Actually WordPress plugin's main file but let's stick with index.php)
  • autoloader.php (A custom autoloader because of custom standards)
  • src/Plugin.php (It supposed to have everything i need for the core like versions, paths etc)
  • src/FrontendScripts.php (It extends a Scripts class and implements a Hook interface)
  • src/BackendScripts.php (It extends a Scripts class and implements a Hook interface)

In index file i do:

$autoloader = new Autoloder();
$autoloader->register();

// so here i can use any of those classes without require them manually.

$plugin = Plugin::getInstance();

$frontend_scripts = new FrontendScripts( 'app', 'test' ); // list of script names that should be registered
$frontend_scripts->hooks(); // Enqueue all the scripts.

$backend_scripts = new BackendScripts( 'admin' ); // the same as for frontend
$backend_scripts->register('admin'); // Enqueue only a single script an example.

What is the best practice of instantiating those FrontendScripts and BackendScripts objects? Should i pass them to the main plugin class as args? Should i just make instances inside the Plugin class without any arguments passed to the main class?

Please sign in or create an account to participate in this conversation.