Instantiating objects

Published 2 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?

PatrickL

I believe what you need to do is require the autoload file.

require_once(__DIR__ . "/autoloader.php");

// Class instantiation here
lievikoff

@PatrickL Thank you for your reply. The code is just an example of the approx implementation. That is more a code design question. I am not sure what is the best OOP approach when you build classes.

youkaihiei

I would pass them in as arguments

lievikoff

@youkaihiei thanks. Are there benefits of passing as arguments?

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