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

yipeiwu_com6年前PHP代码库

工程目录如下:



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

复制代码 代码如下:

<?php
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类的
复制代码 代码如下:

<?php
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
复制代码 代码如下:

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

相关文章

php FLEA中二叉树数组的遍历输出

但是要怎样遍历这个方法产生的二叉树数组呢?以下是我的做法: 复制代码 代码如下: <?php function preTree($cat){ foreach ($cat as $c...

PHP5 面向对象(学习记录)

1,继承extends 只能单继承 public protected private 属性 __construct() __destruct() __get()读取私有成员 __set(...

php中将时间差转换为字符串提示的实现代码

如微博 这看起来更加人性化,好吧,上代码 复制代码 代码如下: <?php class timeAgo { static $timeagoObject; private $rust...

php使用高斯算法实现图片的模糊处理功能示例

php使用高斯算法实现图片的模糊处理功能示例

本文实例讲述了php使用高斯算法实现图片的模糊处理功能。分享给大家供大家参考,具体如下: <?php class image_blur{ function gau...

PHP在字符断点处截断文字的实现代码

复制代码 代码如下: //所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。 // Please acknowledge use of t...