Is it worth checking if class_exists when developing a plugin and how to do it?

Use an auto-loader and let PHP resolve that problem for you. Then only one class will be loaded, and you don’t have to worry about doubled declarations.

Example

I have an (unfinished) plugin Post Notes with the following file structure:

- plugin.php
- php/
   - Nonce_Validator.php
   - Save_Post_Request_Validator.php
   - Textarea.php
   - … and more

This is a very simple plugin, so all files use the same namespace Wpkrauts. In plugin.php, I register a simple auto-loading routine:

spl_autoload_register( function( $name ) {

    $name = ltrim( $name, '\\' );

    if ( 'Wpkrauts' !== strtok( $name, '\\' ) )
        return;

    $file = strtok( '.' );

    $path = __DIR__ . "/php/$file.php";

    if ( file_exists( $path ) )
        require $path;
});

// Now start.
is_admin() && new Post_Notes( 'wpkrauts_post_notes' );

You can do the same without using namespaces (not recommended, exept when you have to support insecure PHP versions like 5.2).

In PHP 5.2 the SPL library can be turned off, but that was never an issue in the plugins I know. Our company distributes plugins like BackWPup with more than a million downloads, and there was never a single compliant about that.

Leave a Comment