PHP autoload

PHP Autoload Usage:

Suppose you have a lot of php file in “my-class” directory. Each file contain php class. You want to call those class from other php file which is out of “my-class” directory. In this case the better way to use php autoload.

function autoload( $class ) {
    $directorys = array();

    //assing your php file directory which file containg your class
    $directorys = array(
        dirname(__FILE__) . '/your-class-directory',
    );

    if( ! count( $directorys ) ) {
        return;
    } 

    foreach( $directorys as $directory ) {

        if( ! is_dir( $directory ) ) {
            echo $directory .' Direcotry is not exist';
            continue;
        }

        if ( ! ( $handle = opendir( $directory ) ) ) {
            echo 'Fail to open your directory. Please check your directory permission';
            continue;
        }

        while ( false !== ( $entry = readdir( $handle ) ) ) {

            if ( $entry != "." && $entry != "..") {

                $file = $directory .'/'. $entry;
                $contents = file_get_contents( $file );
                $contents = str_replace( ' ', '', $contents ); 
                $contents = strtolower( $contents );
                $search = 'class'.$class.'{';

                if ( strpos( $contents, $search ) !== false ) {
                    require_once $directory .'/'. $entry;
                }
            }   
        }
        closedir( $handle );  
    }    
}

spl_autoload_register( 'autoload' );