[关闭]
@Chiang 2020-01-08T01:17:24.000000Z 字数 1964 阅读 581

spl_autoload_register

PHP


spl_autoload_register — 注册给定的函数作为 __autoload 的实现

说明

  1. spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) : bool
  • 将函数注册到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。

范例

spl_autoload_register() 作为 __autoload() 函数的替代

  1. <?php
  2. // function __autoload($class) {
  3. // include 'classes/' . $class . '.class.php';
  4. // }
  5. function my_autoloader($class) {
  6. include 'classes/' . $class . '.class.php';
  7. }
  8. spl_autoload_register('my_autoloader');
  9. // 或者,自 PHP 5.3.0 起可以使用一个匿名函数
  10. spl_autoload_register(function ($class) {
  11. include 'classes/' . $class . '.class.php';
  12. });
  13. ?>

class 未能加载的 spl_autoload_register() 例子

  1. <?php
  2. namespace Foobar;
  3. class Foo {
  4. static public function test($name) {
  5. print '[['. $name .']]';
  6. }
  7. }
  8. spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // 自 PHP 5.3.0 起
  9. new InexistentClass;
  10. //以上例程的输出类似于:
  11. [[Foobar\InexistentClass]]
  12. Fatal error: Class 'Foobar\InexistentClass' not found in ...
  13. ?>

spl_autoload

spl_autoload — __autoload()函数的默认实现

说明

  1. spl_autoload ( string $class_name [, string $file_extensions ] ) : void

本函数提供了__autoload()的一个默认实现。如果不使用任何参数调用 spl_autoload_register() 函数,则以后在进行 __autoload() 调用时会自动使用此函数。

参数

class_name

file_extensions

在默认情况下,本函数先将类名转换成小写,再在小写的类名后加上 .inc 或 .php 的扩展名作为文件名,然后在所有的包含路径(include paths)中检查是否存在该文件。

返回值

没有返回值

spl_autoload_call

spl_autoload_call — 尝试调用所有已注册的__autoload()函数来装载请求类

说明

  1. spl_autoload_call ( string $class_name ) : void

可以直接在程序中手动调用此函数来使用所有已注册的__autoload函数装载类或接口。

参数

class_name
搜索的类名。

返回值

没有返回值

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注