Note 019 automatic loading through spl_autoload_register
Spl_autoload_register
(PHP 5> = 5.1.2, PHP 7)
Spl_autoload_register-registers a given function as the _ autoload implementation
Syntax
Bool spl_autoload_register ([callable $ autoload_function [, bool $ throw = true [, bool $ prepend = false])
Description
Through this function, you can specify the addressing mode for the loaded class, so that you do not need to request and include in large batches. The system automatically searches for classes to be instantiated under the corresponding location according to the specified rules. Although this method is relatively low-level, we generally do not need to do this work when there is a framework. But it is inevitable that I still need to use it. for example, when I write this blog, I need to execute scripts on my own. at this time, I cannot go around. The following example shows a simple automatically loaded program used in my script.
Example
spl_autoload_register(function ($class) { $rootPath = realpath(sprintf('%s/..', __DIR__)); $paths = array( 'src', ); foreach ($paths as $path) { if (is_file( $file = $rootPath . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $class . '.php' )) { include $file; break; } }});
Note: Anonymous functions can be used only in PHP 5.3 and later versions. if you find that they are unavailable, check your PHP version. Here, I simply specify all the classes to be searched under my src folder. the class name is exactly the same as the file name.
The above is the content automatically loaded by note 019 through spl_autoload_register. For more information, see PHP Chinese website (www.php1.cn )!