Home > Article > Backend Development > How to use registration and automatic loading in php classes
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 = '/') { $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. 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 '/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. In this example, the code in require init.php
in test.php is as follows:
<?php require_once 'Init.php'; $dao = new UserDao(); $result = $dao->findByName('zcl'); ?>
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!