©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
(PHP 5 >= 5.1.2)
spl_autoload_register — 注册给定的函数作为 __autoload 的实现
$autoload_function
[, bool $throw
= true
[, bool $prepend
= false
]]] )将函数注册到SPL __autoload函数队列中。如果该队列中的函数尚未激活,则激活它们。
如果在你的程序中已经实现了 __autoload() 函数,它必须显式注册到 __autoload() 队列中。因为 spl_autoload_register() 函数会将Zend Engine中的 __autoload() 函数取代为 spl_autoload() 或 spl_autoload_call() 。
如果需要多条 autoload 函数, spl_autoload_register() 满足了此类需求。 它实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。相比之下, __autoload() 只可以定义一次。
autoload_function
欲注册的自动装载函数。如果没有提供任何参数,则自动注册 autoload 的默认实现函数 spl_autoload() 。
throw
此参数设置了 autoload_function
无法成功注册时,
spl_autoload_register() 是否抛出异常。
prepend
如果是 true, spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
版本 | 说明 |
---|---|
5.3.0 | 引入了命名空间的支持。 |
5.3.0 |
添加了 prepend 参数。
|
Example #1 spl_autoload_register() 作为 __autoload() 函数的替代
<?php
// function __autoload($class) {
// include 'classes/' . $class . '.class.php';
// }
function my_autoloader ( $class ) {
include 'classes/' . $class . '.class.php' ;
}
spl_autoload_register ( 'my_autoloader' );
// 或者,自 PHP 5.3.0 起可以使用一个匿名函数
spl_autoload_register (function ( $class ) {
include 'classes/' . $class . '.class.php' ;
});
?>
Example #2 class 未能加载的 spl_autoload_register() 例子
<?php
namespace Foobar ;
class Foo {
static public function test ( $name ) {
print '[[' . $name . ']]' ;
}
}
spl_autoload_register ( __NAMESPACE__ . '\Foo::test' ); // 自 PHP 5.3.0 起
new InexistentClass ;
?>
以上例程的输出类似于:
[[Foobar\InexistentClass]] Fatal error: Class 'Foobar\InexistentClass' not found in ...
[#1] kakkau at grr dot la [2015-09-28 05:11:28]
A note on registering autoloading functions with additional parameters.
./alf.home.php
<?php
class ALF {
public function haaahaaahaaa($class = "ALF", $param = "Melmac") {
echo "I am ".$class." from ".$param.".\n";
}
}
?>
./kate.melmac.php
<?php
require_once("alf.home.php");
$alf = new ALF();
spl_autoload_register(array($alf,'haaahaaahaaa'));
$alf->haaahaaahaaa(); // ALF is from Melmac :)
@$kate = new Kate(); // this throws a fatal error because
// Kate is NOT from Melmac :)
?>
I am ALF from Melmac.
I am Kate from Melmac.
./kate.earth.php
<?php
require_once("alf.home.php");
spl_autoload_register(function($class){
call_user_func(array(new ALF(),'haaahaaahaaa'), $class, "Earth"); });
@$kate = new Kate(); // Kate is from Earth :)
?>
I am Kate from Earth.
[#2] eyeofmidas at gmail dot com [2015-08-12 15:57:52]
When switching from using __autoload() to using spl_autoload_register keep in mind that deserialization of the session can trigger class lookups.
This works as expected:
<?php
session_start();
function __autoload($class) {
...
}
?>
This will result in "__PHP_Incomplete_Class_Name" errors when using classes deserialized from the session.
<?php
session_start();
function customAutoloader($class) {
...
}
spl_autoload_register("customAutoloader");
?>
So you need to make sure the spl_autoload_register is done BEFORE session_start() is called.
CORRECT:
<?php
function customAutoloader($class) {
...
}
spl_autoload_register("customAutoloader");
session_start();
?>
[#3] iam at thatguy dot co dot za [2015-05-08 07:19:03]
<?php
// Example to auto-load class files from multiple directories using the SPL_AUTOLOAD_REGISTER method.
// It auto-loads any file it finds starting with class.<classname>.php (LOWERCASE), eg: class.from.php, class.db.php
spl_autoload_register(function($class_name) {
// Define an array of directories in the order of their priority to iterate through.
$dirs = array(
'project/', // Project specific classes (+Core Overrides)
'classes/', // Core classes example
'tests/', // Unit test classes, if using PHP-Unit
);
// Looping through each directory to load all the class files. It will only require a file once.
// If it finds the same class in a directory later on, IT WILL IGNORE IT! Because of that require once!
foreach( $dirs as $dir ) {
if (file_exists($dir.'class.'.strtolower($class_name).'.php')) {
require_once($dir.'class.'.strtolower($class_name).'.php');
return;
}
}
});
[#4] xavier dot bouhours at free dot fr [2015-03-03 15:55:02]
// Get last class version
if( !function_exists('classAutoLoader') )
{
function classAutoLoader($className)
{
$classFiles = array() ;
$classFile = FALSE ;
$classDir = __DIR__ .'/' ;
// Get all files
$files = scandir( $classDir ) ;
foreach ( $files as $url )
{
// Verifie if file is : Name + class + version + extension
if( is_file($classDir.$url) && preg_match('/([^\.]+)\.class\.([\d\.]+)\.(.+)$/', $url, $m ) )
{
// Verifie finded file
if( $className == $m[1] )
{
// Get previous version or init
$previous = isset( $classFiles[$m[1]] ) ? $classFiles[$m[1]] : 0 ;
// Get last version
if( $previous<$m[2] )
{
$classFiles[ $m[1] ] = $m[2] ; // version
$classFile = $classDir.$url ;
}
}
}
} ;
if( !class_exists($className) ) include( $classFile );
}
}
spl_autoload_register('classAutoLoader') ;
[#5] neolium at gmail dot com [2015-02-13 13:00:09]
This autoload will find every class you call if you put each one in a different file.
It walks into every directory recursivly from the root you specify in the $root var.
You can specify the folders ou don't want to walk in (e.g you won't find any class in a 'view' folder on an MVC project) in the $dir_to_not_look_in array;
spl_autoload_register(function($class) {
$root = 'my/root/path';
$file = $class . '.php';
$dir_to_not_look_in = array($directories, $to, $not, $look, $in);
if(!function_exists('load')) {
function load($dir, $file) {
if(file_exists($dir . '/' . $file)) {
require_once $dir . '/' . $file;
} else {
foreach(scandir($dir) as $value) {
if(is_dir($dir. '/' . $value) && !in_array($value, $dir_to_no_look_in))
load($dir. '/' . $value, $file);
}
}
};
}
load($root, $file);
});
[#6] nmmm at nmmm dot nu [2014-06-04 14:17:21]
spl_autoload_register() can be used with include_path.
suppose in current directory we have directory "a", and inside there is directory "test" and inside is test.php :
<?php
namespace test;
class test{
function __construct(){
echo "Test created\n";
}
}
?>
then we can use following code to load the class:
<?php
ini_set("include_path", "./a/");
spl_autoload_register();
$t = new \test\test();
?>
[#7] hajo-p [2014-01-05 17:25:06]
if you have a dir-structure like "/abc/def/ghi", your index.php lies in the top directory, but you want to use namespaces starting with "def" or "ghi":
you can switch the namespace root directory of php with e.g. set_include_path(__DIR__ . '/abc') and afterwards define + use your namespaces with the simple spl_autoload_register() function without any arguments supplied.
remember that php handlers "cli" and "cli-server" are special cases.
[#8] Kurd the Great [2013-10-01 16:13:03]
if(!defined('BASE_PATH')) {
define('BASE_PATH', dirname(__FILE__) . '/');
require BASE_PATH . 'Autoloader.php';
Autoloader::Register();
}
class Autoloader
{
public static function Register() {
return spl_autoload_register(array('Autoloader', 'Load'));
}
public static function Load($strObjectName) {
if(class_exists($strObjectName) === false) {
return false;
}
$strObjectFilePath = BASE_PATH . $strObjectName . '.php';
if((file_exists($strObjectFilePath) === false) || (is_readable($strObjectFilePath) === false)) {
return false;
}
require($strObjectFilePath);
}
}
[#9] phil at propcom dot co dot uk [2013-09-18 08:36:49]
It is important to note that the autoloader will NOT be called if an E_STRICT error triggers the error handler which, in turn, tries to use classes which are not yet loaded.
In this instance, you should manually load classes required by the error handler.
[#10] ali dot taheri dot m at gmail dot com [2013-07-24 14:23:06]
I've made a little function that makes and registers a loader that seems to be safe and reliable although I'm not sure but it feels like a good idea to share, it took me some time to come up with it I hope it saves someone some time,
<?php
function Loader($root = "") {
$loaderFunction = create_function('$class', 'include "' . $root . '$class.php";');
spl_autoload_register($loaderFunction);
}
?>
if you have a file system exactly like your directory tree this function works perfectly, I haven't tested it on unix, but on windows, the default loader fails when your webpage isn't in the root directory, this makes sure that it won't cause a problem if your webpage is on a subdir too just pass ../ or more drived ../../ as root and it will work like a charm, note that i couldn't use anonymous functions because then the $root variable wouldn't have the same scope as the Loader function, so the function must be created on the fly. this is a good example of this functions usage
your class:
root/classes/support/classic.php
<?php
namespace classes/support;
class classic {
// class def
}
?>
root/support/index.php
<?php
Loader('../');
use classes/support/classic;
$cls = new classic();
//use $cls
?>
the loader will make a function like this:
<?php
function($class) {
include "../$class.php";
}
//when and when the class is needed this will run the script which is indeed what we need:
include '../classes/support/classic.php';
?>
hope this helps folks;
[#11] sebastian at 34n dot de [2013-05-24 09:49:19]
You can also use it like this:
> spl_autoload_register ( array( new AutoloaderClass, 'method') );
or in PHP > 5.3:
> spl_autoload_register ( [ new My\Namespace\Autoloader, 'method'] );
On this way you dont have to create a variable, which is used once.
[#12] a dot schaffhirt at sedna-soft dot de [2013-04-07 13:42:55]
What I said here previously is only true on Windows. The built-in default autoloader that is registered when you call spl_autoload_register() without any arguments simply adds the qualified class name plus the registered file extension (.php) to each of the include paths and tries to include that file.
Example (on Windows):
include paths:
- "."
- "d:/projects/phplib"
qualified class name to load:
network\http\rest\Resource
Here's what happens:
PHP tries to load
'.\\network\\http\\rest\\Resource.php'
-> file not found
PHP tries to load
'd:/projects/phplib\\network\\http\\rest\\Resource.php'
-> file found and included
Note the slashes and backslashes in the file path. On Windows this works perfectly, but on a Linux machine, the backslashes won't work and additionally the file names are case-sensitive.
That's why on Linux the quick-and-easy way would be to convert these qualified class names to slashes and to lowercase and pass them to the built-in autoloader like so:
<?php
spl_autoload_register(
function ($pClassName) {
spl_autoload(strtolower(str_replace("\\", "/", $pClassName)));
}
);
?>
But this means, you have to save all your classes with lowercase file names. Otherwise, if you omit the strtolower call, you have to use the class names exactly as specified by the file name, which can be annoying for class names that are defined with non-straightforward case like e. g. XMLHttpRequest.
I prefer the lowercase approach, because it is easier to use and the file name conversion can be done automatically on deploying.
[#13] daniel at amnistechnology dot com [2012-10-17 09:57:12]
Cleverly - and usefully - I have noticed that (on PHP 5.3 at least) these autoloaders "kick in" even when you call a public static method of an as-yet-unloaded all static class.
[#14] Anonymous [2012-02-03 16:52:20]
Note that when specifying the third parameter (prepend), the function will fail badly in PHP 5.2
[#15] (delphists) at (apollo) dot (lv) [2011-02-01 01:57:34]
When using spl_autoload_register() with class methods, it might seem that it can use only public methods, though it can use private/protected methods as well, if registered from inside the class:
<?php
class ClassAutoloader {
public function __construct() {
spl_autoload_register(array($this, 'loader'));
}
private function loader($className) {
echo 'Trying to load ', $className, ' via ', __METHOD__, "()\n";
include $className . '.php';
}
}
$autoloader = new ClassAutoloader();
$obj = new Class1();
$obj = new Class2();
?>
Output:
--------
Trying to load Class1 via ClassAutoloader::loader()
Class1::__construct()
Trying to load Class2 via ClassAutoloader::loader()
Class2::__construct()
[#16] anthon at piwik dot org [2010-07-04 21:02:15]
Think twice about throwing an exception from a registered autoloader.
If you have multiple autoloaders registered, and one (or more) throws an exception before a later autoloader loads the class, stacked exceptions are thrown (and must be caught) even though the class was loaded successfully.
[#17] sebastian dot krebs at kingcrunch dot de [2010-03-24 10:54:17]
It seems, that spl_autoload tests, if the class exists, after calling every registered loader. So it breaks the chain, if the class exists and will not call the other loaders
<?php
function a ($c) {
echo "a\n";
class Bla {} // Usually "include 'path/to/file.php';"
}
function b ($c) {
echo "b\n";
}
spl_autoload_register('a');
spl_autoload_register('b');
$c = new Bla();
?>
[#18] Anonymous [2010-03-16 20:30:42]
Be careful using this function on case sensitive file systems.
<?php
spl_autoload_extensions('.php');
spl_autoload_register();
?>
I develop on OS X and everything was working fine. But when releasing to my linux server, none of my class files were loading. I had to lowercase all my filenames, because calling a class "DatabaseObject" would try including "databaseobject.php", instead of "DatabaseObject.php"
I think i'll go back to using the slower __autoload() function, just so i can keep my class files readable
[#19] rayro at gmx dot de [2010-01-04 03:14:51]
It is never a good idea and a unconscienable concept to create the classes in the autoload function via eval.
It should be a nice feature with these Exception, but i think anyone is able to handle it without this method although. Atm i dont realize for what this is good for...
As i might note, class_exists() will ever define the classes u only want to check for existance, and will therefor ever return true:
<?php
function EvalIsEvil($class) {
eval('class '.$className.'{}');
}
spl_autoload_register('EvalIsEvil');
if (class_exists($s="IsMyModuleHere")) {
// this is no module, but get there with eval()...
return new $s();
}
?>
[#20] a dot schaffhirt at sedna-soft dot de [2009-07-27 19:05:03]
Good news for PHP 5.3 users with namespaced classes:
When you create a subfolder structure matching the namespaces of the containing classes, you will never even have to define an autoloader.
<?php
spl_autoload_extensions(".php"); // comma-separated list
spl_autoload_register();
?>
It is recommended to use only one extension for all classes. PHP (more exactly spl_autoload) does the rest for you and is even quicker than a semantically equal self-defined autoload function like this one:
<?php
function my_autoload ($pClassName) {
include(__DIR__ . "/" . $pClassName . ".php");
}
spl_autoload_register("my_autoload");
?>
I compared them with the following setting: There are 10 folders, each having 10 subfolders, each having 10 subfolders, each containing 10 classes.
To load and instantiate these 1000 classes (parameterless no-action constructor), the user-definded autoload function approach took 50ms longer in average than the spl_autoload function in a series of 10 command-line calls for each approach.
I made this benchmark to ensure that I don't recommend something that could be called "nice, but slow" later.
Best regards,
[#21] stanlemon at mac dot com [2007-09-28 10:20:04]
Editorial note: The appropriate PHP bug that requests behavior this function emulates is http://bugs.php.net/bug.php?id=42823 . This function does NOT work if there has been an array($obj, 'nonStaticMethod') registered in the autoload stack--while the autoload will be removed, it will be re-registered incorrectly.
The spl_autoload_register() method registers functions in its stack in the order that spl_autoload_register() was called, and subsequently if you want an autoload function to override previous autoload functions you will either need to unregister the previous ones or change the order of the autoload stack.
For example, say in your default implementation of an autoload function you throw an exception if the class cannot be found, or perhaps a fatal error. Later on in your code you add a second implementation of an autoload function which will load a library that the previous method would fail on. This will not call the second autoloader method first, but rather will continue to error out on the first method.
As previously mentioned, you can unregister the existing autoloader that errors out, or you can create a mechanism for unregistering and re-registering the autoloaders in the order you want.
Here is a sample/example of how you might consider re-registering autoloaders so that the newest autoloader is called first, and the oldest last:
<?php
// Editorial notes: Small bug and compatibility fixes
// added to the function
function spl_autoload_preregister( $autoload ) {
// No functions currently in the stack.
if ( ($funcs = spl_autoload_functions()) === false ) {
spl_autoload_register($autoload);
} else {
// Unregister existing autoloaders...
$compat =
version_compare(PHP_VERSION, '5.1.2', '<=') &&
version_compare(PHP_VERSION, '5.1.0', '>=');
foreach ($funcs as $func) {
if (is_array($func)) {
// :TRICKY: There are some compatibility issues and some
// places where we need to error out
$reflector = new ReflectionMethod($func[0], $func[1]);
if (!$reflector->isStatic()) {
throw new Exception('
This function is not compatible
with non-static object methods due to PHP Bug #44144.
');
}
// Suprisingly, spl_autoload_register supports the
// Class::staticMethod callback format, although call_user_func doesn't
if ($compat) $func = implode('::', $func);
}
spl_autoload_unregister($func);
}
// Register the new one, thus putting it at the front of the stack...
spl_autoload_register($autoload);
// Now, go back and re-register all of our old ones.
foreach ($funcs as $func) {
spl_autoload_register($func);
}
}
}
?>
Note: I have not tested this for overhead, so I am not 100% sure what the performance implication of the above example are.
[#22] harvey dot NO_SPAM dot robin at gmail dot com [2007-02-10 05:54:22]
This function is smart enough not to add the same loader twice. This seems to work for all of the different loader formats. Example:
<?php
class ALoader
{
static function load($class) { return true; }
}
function anotherLoader($class) {
return true;
}
$F = new ALoader;
spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array($F, 'load'));
spl_autoload_register('anotherLoader');
spl_autoload_register('anotherLoader');
var_dump(spl_autoload_functions());
?>
[#23] florent at mediagonale dot com [2006-11-14 01:19:28]
If your autoload function is a class method, you can call spl_autoload_register with an array specifying the class and the method to run.
* You can use a static method :
<?php
class MyClass {
public static function autoload($className) {
// ...
}
}
spl_autoload_register(array('MyClass', 'autoload'));
?>
* Or you can use an instance :
<?php
class MyClass {
public function autoload($className) {
// ...
}
}
$instance = new MyClass();
spl_autoload_register(array($instance, 'autoload'));
?>