PHP __autoload 和 spl的autoload 函数研究

__autoload()

这个函数会在试图使用尚未被定义的类时自动调用,缺点是整个项目只能有一个该函数。改函数被调用的时机是在每个类被使用时。

a.php:

echo "a.php"."<br/>";
function __autoload($class){
  echo "__autoload"."<br/>";
  include_once($class.".php");
}

$a=new BB();
echo "--------------"."<br/>";
$b=new CC();

b.php:

class BB{
  function __construct(){
    echo  "BB construct"."<br/>";
  }
}

c.php
class CC{
  function __construct(){
    echo  "CC construct"."<br/>";
  }
}

运行a.php,输出结果:

$ php a.php

a.php
__autoload
BB construct
--------------
__autoload
CC construct

spl函数

  1. spl_autoload()
  2. spl_autoload_call()
  3. spl_autoload_extensions()
  4. spl_autoload_register()
  5. spl_autoload_functions()
  6. spl_autoload_unregister()

spl_autoload() 和 spl_autoload_extensions()

函数定义:

void spl_autoload(string $class_name [, string $file_extensions = spl_autoload_extensions() ])
string spl_autoload_extensions ([ string $file_extensions ] )

spl_autoload() 函数是默认的 __autoload() 函数的实现,比 __autoload() 函数多了一个 $file_extensions 参数,该参数可以制定默认加载的文件后缀名,默认值是 spl_autoload_extensions() 函数的返回值。

spl_autoload_extensions() 函数可以设置 spl_autoload() 函数的默认加载文件的后缀名。默认的后缀为 .inc, .php

比如我们有2个文件a.php,b.php在同一个目录下,a.php内容:

spl_autoload_register();
$a=BB();

b.php内容和上边一样,运行输出:

BB construct

这里我们先调用了 spl_autoload_register() 函数,该函数默认注册 spl_autoload() 函数

spl_autoload() 函数的调用时机和 __autoload() 函数一样,在每个类被使用的时候。

spl_autoload_call()

函数定义:

void spl_autoload_call ( string $class_name )

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

spl_autoload_register() , spl_autoload_unregister() , spl_autoload_functions()

函数定义:

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
bool spl_autoload_unregister ( mixed $autoload_function )
array spl_autoload_functions ( void )

spl_autoload_register() 用来添加新的 autoload 函数,用来删除添加的 autolaod 函数, spl_autoload_functions 用来显示已经注册的 autoload 函数

sql提供函数之间的关系

markdown 图文有点麻烦,直接我word上的截图

QQ20170210-175548.png

QQ20170210-175640.png

QQ20170210-175654.png

QQ20170210-175724.png

此时如果我们手动调用 spl_autoload_call('bb') 那么php会遍历 autoload 函数列表,顺序执行 myload()myload2222()

如果我们不手动执行 spl_autoload_call() 那么当遇到 $a=new bb()$b=CC::getInstance() 这些调用类的函数时,会自动调用 spl_autoload_call('bb'); spl_autoload_call('CC');

标签: php