Home  >  Article  >  Backend Development  >  How to use registration and automatic loading in php classes

How to use registration and automatic loading in php classes

伊谢尔伦
伊谢尔伦Original
2017-07-01 09:52:46955browse

This article is a detailed analysis and introduction to the registration and automatic loading of PHP classes. Friends in need can refer to the

project directory as follows:



1. Put the classes that need to be registered in an array

The code is as follows:

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


2. Registration array
Note:
The class paths in step 1 are relative to init.php, not Compared with Utils, this is because we use the automatic loading function spl_autoload_register in init.php to require the code of the class is as follows:

<?php
require_once
 &#39;/Utils/Utils.php&#39;;
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 ( &#39;UTF-8&#39; );
        //registe classes
        spl_autoload_register ( array ($this,&#39;loadClass&#39; ) );
    }
    /**
     * Class loader.
     */
    public function loadClass($name) {
        $classes = Utils::getClasses ();
        if (! 
array_key_exists
 ( $name, $classes )) {
            die ( &#39;Class "&#39; . $name . &#39;" not found.&#39; );
        }
        require_once $classes [$name];
    }
}
$init = new Init ();
$init->init ();
?>

3. In this example, the code in require init.php



in test.php is as follows:

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

The above is the detailed content of How to use registration and automatic loading in php classes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn