略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: spl_autoload_call

2024-12-22

spl_autoload_call

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

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

说明

spl_autoload_call(string $class_name): void

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

参数

class_name

搜索的类名。

返回值

没有返回值。

add a noteadd a note

User Contributed Notes 2 notes

up
2
k dot varmark at gmail dot com
11 years ago
It should be noted, that calling spl_autoload_call on a child class, and then on its parent class, throws a fatal error.

This happens because autoloading the child class also loads the class it extends. And since spl_autoload_call forcibly calls the registered autoload function(s), not taking into account whether the class exists, a fatal error is thrown:

File: child.class.php

<?php
class Child extends Parent () {
    public function
__construct () {
       
parent::__construct();
    }
}
?>

File: parent.class.php

<?php
class Parent () {
    public function
__construct () {

    }
}
?>

File: autoload.php

<?php

/*    works fine    */
   
spl_autoload_call('Child');

/*    throws: Fatal error: Cannot redeclare class Parent in /parent.class.php on line 2    */
   
spl_autoload_call('Parent');

?>
up
0
Melnofil
1 year ago
A complete example with namespaces:

fruits/pinapple.php

<?php
namespace Fruits;
echo
"pinapple\n";
class
Pinapple { }
?>

fruits/pinapple.php

<?php
namespace Vegetables;
use
Fruits\Pinapple;
echo
"carrot\n";
class
Carrot { }
new
Pinapple(); // Let's call autoload here
?>

index.php

<?php
spl_autoload_register
(function($class_name) {
    @include_once(
__DIR__ . '/' . strtolower(str_replace('\\', '/', $class_name)) . '.php');
});
new
Vegetables\Carrot();
?>

Result:

carrot
pinapple

index2.php

<?php
spl_autoload_register
(function($class_name) {
    @include_once(
__DIR__ . '/' . strtolower(str_replace('\\', '/', $class_name)) . '.php');
});
spl_autoload_call('Fruits\\Pinapple'); // Reverse the load order
spl_autoload_call('Fruits\\Pinapple'); // Multiple call is safe with include_once
new Vegetables\Carrot();
?>

Result:

pinapple
carrot

官方地址:https://www.php.net/manual/en/function.spl-autoload-call.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3