Last active
October 9, 2024 00:31
-
-
Save sheabunge/50a9d9f8234820a989ab to your computer and use it in GitHub Desktop.
Basic PHP class autoloader that follows the WordPress coding standards for class names and class filenames
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Shea\Example_Plugin; | |
/** | |
* Enable autoloading of plugin classes in namespace. | |
* | |
* @param $class_name | |
*/ | |
function autoload( $class_name ) { | |
// Only autoload classes from this namespace. | |
if ( false === strpos( $class_name, __NAMESPACE__ ) ) { | |
return; | |
} | |
// Remove namespace from class name. | |
$class_file = str_replace( __NAMESPACE__ . '\\', '', $class_name ); | |
// Convert class name format to file name format. | |
$class_file = str_replace( '_', '-', strtolower( $class_file ) ); | |
// Convert sub-namespaces into directories. | |
$class_path = explode( '\\', $class_file ); | |
$class_file = array_pop( $class_path ); | |
$class_path = implode( '/', $class_path ); | |
// Load the class. | |
require_once sprintf( '%s/php/%s/class-%s.php', __DIR__, $class_path, $class_file ); | |
} | |
spl_autoload_register( __NAMESPACE__ . '\autoload' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@arvilmena you could use it in the main file of a plugin or the functions.php file of a theme, before loading any of the associated classes.