PHP 8.1.6 Released!

类的自动加载

在编写面向对象(OOP) 程序时,很多开发者为每个类新建一个 PHP 文件。 这会带来一个烦恼:每个脚本的开头,都需要包含(include)一个长长的列表(每个类都有个文件)。

spl_autoload_register() 函数可以注册任意数量的自动加载器,当使用尚未被定义的类(class)和接口(interface)时自动去加载。通过注册自动加载器,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

警告

PHP 8.0.0 之前,可以使用 __autoload() 自动加载类和接口。然而,它是 spl_autoload_register() 的一种不太灵活的替代方法,并且 __autoload() 在 PHP 7.2.0 起弃用,在 PHP 8.0.0 起移除。

示例 #1 自动加载示例

本例尝试分别从 MyClass1.phpMyClass2.php 文件中加载 MyClass1MyClass2 类。

<?php
spl_autoload_register
(function ($class_name) {
    require_once 
$class_name '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>

示例 #2 另一个例子

本例尝试加载接口 ITest

<?php

spl_autoload_register
(function ($name) {
    
var_dump($name);
});

class 
Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

示例 #3 自动加载异常处理

本例抛出一个异常并在 try/catch 语句块中演示。

<?php
spl_autoload_register
(function ($name) {
    echo 
"Want to load $name.\n";
    throw new 
Exception("Unable to load $name.");
});

try {
    
$obj = new NonLoadableClass();
} catch (
Exception $e) {
    echo 
$e->getMessage(), "\n";
}
?>

以上例程会输出:

Want to load NonLoadableClass.
Unable to load NonLoadableClass.

示例 #4 自动加载异常处理 - 没有自定义异常机制

本例将一个异常抛给不存在的自定义异常处理函数。

<?php
spl_autoload_register
(function ($name) {
    echo 
"Want to load $name.\n";
    throw new 
MissingException("Unable to load $name.");
});

try {
    
$obj = new NonLoadableClass();
} catch (
Exception $e) {
    echo 
$e->getMessage(), "\n";
}
?>

以上例程会输出:

Want to load NonLoadableClass.
Want to load MissingException.

Fatal error: Class 'MissingException' not found in testMissingException.php on line 4

add a note add a note

User Contributed Notes 5 notes

up
96
jarret dot minkler at gmail dot com
13 years ago
You should not have to use require_once inside the autoloader, as if the class is not found it wouldn't be trying to look for it by using the autoloader.

Just use require(), which will be better on performance as well as it does not have to check if it is unique.
up
58
str at maphpia dot com
5 years ago
This is my autoloader for my PSR-4 clases. I prefer to use composer's autoloader, but this works for legacy projects that can't use composer.

<?php
/**
* Simple autoloader, so we don't need Composer just for this.
*/
class Autoloader
{
    public static function
register()
    {
       
spl_autoload_register(function ($class) {
           
$file = str_replace('\\', DIRECTORY_SEPARATOR, $class).'.php';
            if (
file_exists($file)) {
                require
$file;
                return
true;
            }
            return
false;
        });
    }
}
Autoloader::register();
up
19
toi]n[enkayt[attaat]gmaal.com
2 years ago
Autoloading plain functions is not supported by PHP at the time of writing. There is however a simple way to trick the autoloader to do this. The only thing that is needed is that the autoloader finds the searched class (or any other autoloadable piece of code) from the files it goes through and the whole file will be included to the runtime.

Let's say you have a namespaced file for functions you wish to autoload. Simply adding a class of the same name to that file with a single constant property is enough to trigger the autoloader to seek for the file. Autoloading can then be triggered by accessing the constant property.

The constant could be replaced by any static property or method or by default constructor. However, I personally find a constant named 'load' elegant and informative. After all this is a workaround. Another thing to keep in mind is that this introduces an unnecessary class to the runtime. The benefit of this is that there is no need to manually include or require files containing functions by path which in turn makes code maintaining easier. Such behaviour makes it easier to alter the project structure since manual includes need not to be fixed. Only the autoloader needs to be able to locate the moved files which can be automated.

A code file containing functions.
/Some/Namespace/Functions.php
<?php
namespace Some\Namespace;

class
Functions { const load = 1; }

function
a () {
}

function
b () {
}
?>

Triggering autoloading of the file containing functions.
main.php
<?php
\Some\Namespace\Functions::load;

a ();
b ();
?>
up
11
Anonymous
12 years ago
It's worth to mention, if your operating system is case-sensitive you need to name your file with same case as in source code eg. MyClass.php instead of myclass.php
up
2
kalkamar at web dot de
13 years ago
Because static classes have no constructor I use this to initialize such classes.
The function init will (if available) be called when you first use the class.
The class must not be included before, otherwise the init-function wont be called as autoloading is not used.

<?php
function __autoload($class_name)
{
    require_once(
CLASSES_PATH.$class_name.'.cls.php');
    if(
method_exists($class_name,'init'))
       
call_user_func(array($class_name,'init'));
    return
true;
}
?>

I use it for example to establish the mysql-connection on demand.

It is also possilbe do add a destructor by adding this lines to the function:
<?php
if(method_exists($class_name,'destruct'))
   
register_shutdown_function(array($class_name,'destruct'));
?>
To Top