Heim  >  Artikel  >  Backend-Entwicklung  >  解析php类的注册与自动加载_PHP教程

解析php类的注册与自动加载_PHP教程

WBOY
WBOYOriginal
2016-07-21 15:01:32704Durchsuche

工程目录如下:



1、将需要注册的类放在一个数组中

复制代码 代码如下:

final class Utils {
    private function __construct() {
    }
    public static function getClasses($pre_path = '/') {
        $classes = array(
                'DBConfig' => $pre_path.'DBConfig/DBConfig.php',
                'User' => $pre_path.'Model/User.php',
                'Dao' => $pre_path.'Dao/Dao.php',
                'UserDao' => $pre_path.'Dao/UserDao.php',
                'UserMapper' => $pre_path.'Mapping/UserMapper.php',
        );
        return $classes;
    }
}
?>

2、注册数组
注意:
步骤1中的类的路径都是相对于init.php而言的,不是相对于Utils而言的,这是因为我们通过init.php里的自动加载函数spl_autoload_register来require类的
复制代码 代码如下:

require_once '/Utils/Utils.php';
final class Init {

    /**
     * System config.
     */
    public function init() {
        // error reporting - all errors for development (ensure you have
        // display_errors = On in your php.ini file)
        error_reporting ( E_ALL | E_STRICT );
        mb_internal_encoding ( 'UTF-8' );
        //registe classes
        spl_autoload_register ( array ($this,'loadClass' ) );
    }

    /**
     * Class loader.
     */
    public function loadClass($name) {
        $classes = Utils::getClasses ();
        if (! array_key_exists ( $name, $classes )) {
            die ( 'Class "' . $name . '" not found.' );
        }
        require_once $classes [$name];
    }
}
$init = new Init ();
$init->init ();
?>

3、本例中在使用处test.php里require init.php
复制代码 代码如下:

require_once 'Init.php';
$dao = new UserDao();
$result = $dao->findByName('zcl');
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/327995.htmlTechArticle工程目录如下: 1、将需要注册的类放在一个数组中 复制代码 代码如下: ?php final class Utils { private function __construct() { } public static function g...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn