I have been learning about namespaces and autoloading for my latest Wordpress plugin.
I am having an issue working out if it is possible to use an autoloader to statically instantiate classes too.
What I have done so far
I have added this autoloader to my plugin file:
spl_autoload_register( 'bnfoAutoload' );
function bnfoAutoload( $class ) {
// project-specific namespace prefix
$prefix = 'BnfoAutoload\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/';
// does the class use the namespace prefix?
$len = strlen( $prefix );
if ( strncmp( $prefix, $class, $len ) !== 0 ) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr( $class, $len );
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace( '\\', '/', $relative_class ) . '.php';
// if the file exists, require it
if ( file_exists( $file ) ) {
require $file;
}
}
I have got autoloading to work effectively for newly instanstiated instances of a class e.g.:
$response = new BnfoAutoload\Includes\Tester();
$exact_response = $response->testFunction();
and through reading this SO post when calling static methods e.g.
BnfoAutoload\Includes\Tester::testStaticFunction()
Context
However, occasionally I want to statically instantiate a class, for example if I want to add a filter.
e.g. this would be 'classfile.php';
namespace BnfoAutoload\Includes\
class LoadClass {
public function __construct() {
add_action( 'wp_head', [ $this, 'loadFunction' ];
}
public function loadFunction() {
// something
}
}
new LoadClass();
Potential solutions
Option 1: I can manually require classfile.php in my plugin file, which would then statically instantiate the class.
require_once ('classfile.php' );
Option 2: I can instantiate these static classes in the plugin file, at which point they are picked up by the autoloader
new BnfoAutoload\Includes\LoadClass();
I am not sure if either of these is correct so any alternative thoughts much appreciated.