Skip to content

Instantly share code, notes, and snippets.

@emgk
Last active April 22, 2018 00:30
Show Gist options
  • Save emgk/b98ccf6044143d2a236934bd5c366905 to your computer and use it in GitHub Desktop.
Save emgk/b98ccf6044143d2a236934bd5c366905 to your computer and use it in GitHub Desktop.
How to use spl_autoload_register() function to load all classes from plugin.
<?php
/**
* Plugin Name: Class Autoloader
* Author: Govind
* Author URI: http://emgk.github.io
* Email: [email protected]
*
* Suppose, In our WP plugin we have three classes inside 'classes' folder.
* to load them without long lines of require_once statements, then in that
* case we have to use spl_autoload_register() function.
*
* Plugin folder structure
*
* - Plugin Root Folder
* +-- classes [DIR]
* +-- class-wpauto-first.php [FILE]
* +-- class-wpauto-second.php [FILE]
* +-- class-wpauto-third.php [FILE]
* +-- autoloader-main.php [FILE]
*/
// Registering our function into spl_autoload_register().
spl_autoload_register('autoloadclass');
// Define our function to load our classes.
function autoloadclass($classname){
/*
* As our class name is like WPAUTO_First,WPAUTO_Second,WPAUTO_Third,
* we've added 'WPAUTO' as class prefix to distinct them from other classes.
* So that we can identify our classes.
*
*/
// exploding classname using '_' to get the prefix of our class.
$classprefix = explode('_',strtolower($classname));
// verify if class name containing 'wpauto' as prefix.
if( 'wpauto' !== $classprefix[0] )
return;
// prepare the path of class folder.
$dir = plugin_dir_path( __FILE__ ) . 'classes/';
// generate file name from Class name.
// 'AUTO_First' will be 'class-auto-first.php'
$classfile = 'class-' . str_replace('_', '-', strtolower( $classname ) ) . '.php';
// checking if file exists or not.
if ( file_exists( $classfile ) )
include $classfile;
}
?>
<?php
class AUTO_First{
public function printdata(){
echo 'I am inside first class!';
}
}
<?php
class AUTO_Second{
public function printdata(){
echo 'I am inside Second class!';
}
}
<?php
class AUTO_Third{
public function printdata(){
echo 'I am inside third class!';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment