1. 程式人生 > >php自動載入指定目錄下的類檔案

php自動載入指定目錄下的類檔案

網上找到的類,非常有用,檔名: autoload.php

<?php
/**
 * Created by PhpStorm.
 * User: zcm
 * Mail: [email protected]
 * Date: 2018/10/10 上午10:20
 */

if(!defined('ROOTDIR'))
{
	define('ROOTDIR', realpath(__DIR__ . '/../'));
}

class Autoloader {

	public static function myAutoload( $name )
	{
		$class_path = str_replace('\\',DIRECTORY_SEPARATOR, $name);
		$file = ROOTDIR . '/' . $class_path . '.php';
		if( file_exists( $file ) )
		{
			require_once( $file );
			if( class_exists($name, false) )
			{
				return true;
			}
		}
		return false;
	}
}

spl_autoload_register('Autoloader::myAutoload');

使用時,只要require/require_once 此檔案即可,想用的類即可找到了!