The autoload mechanism makes it possible for PHP programs to automatically include class files when using classes, rather than having all the class files included in the first place, which is also known as lazy loading.
The following is an example of using the autoload mechanism to load the person class:
The code is as follows |
Copy Code |
/* autoload.php */ function __autoload ($classname) { Require_once ($classname. "class.php"); } $person = new Person ("Altair", 6); Var_dump ($person); ?> |
Implementation of PHP's autoload mechanism
To implement the auto-load class in PHP, it's a magic method, __autoload (); This is the auto-load class method that PHP5 adds. As long as the function is defined, if PHP is run to a class that cannot be found, it will be looked up according to the rules of __autoload.
Oneself also plan, with Set_include_path and get_include_path to use, make automatic loading class more perfect point, code out (imitate Magento):
The code is as follows |
Copy Code |
$paths [] = BP. Ds. ' App '. Ds. ' Local '; $paths [] = BP. Ds. ' App '. Ds. ' Base '; $paths [] = BP. Ds. ' Lib '; $appPath = Implode (PS, $paths); Set_include_path ($appPath. Ps. Get_include_path ()); |
So you can add the default class loading environment for PHP, here just add the path to the PHP environment, if you want to continue to add rules, you can define the __autoload function, but I am here to use the object, then replaced by a method: Spl_autoload_register method, Below is oneself according to the rule of Magento, oneself get a set, actually with magento similar.
code as follows |
copy code |
Class Autoload { /** * Self-object * */ protected static $_instance = NULL; Public Function __construct () { } /* * Instantiation of itself * */ public static function instance () { if (null = = Self::$_instance) { Self::$_instance = new self (); } return self::$_instance; } /** * * Register Auto-load function */ public static function register () { Spl_autoload_register (Array (self::instance (), ' autoload ')); } /* * * Auto Load Class */ Public Function AutoLoad ($class) { if (!is_string ($class)) { Return } $classFile = Str_replace (', DS, Ucwords (Str_replace (' _ ', ' ', $class))); $classFile. = '. php '; return include $classFile; } } |
http://www.bkjia.com/PHPjc/633080.html www.bkjia.com true http://www.bkjia.com/PHPjc/633080.html techarticle The autoload mechanism makes it possible for PHP programs to automatically include class files when using classes, rather than having all the class files included in the first place, which is also known as lazy loading. The next ...