告别手动引入!PHP自动加载终极指南,效率提升90%

在没有自动加载机制的前提下,想要使用不同文件的类时,需要逐个手动将文件引入才行

require 'classes/MyClass.php';
// ......

$obj = new MyClass();

这种情况会导致维护困难,随着项目扩大变得难以管理。因此自动加载是PHP中一种重要的机制。

自动加载

允许在首次使用类时动态加载类文件,而不需要手动包含每个类文件

PHP中推荐使用spl_autoload_register函数实现自动加载/注册

/**
 * Register given function as __autoload() implementation
 * @link https://php.net/manual/en/function.spl-autoload-register.php
 * @param callable|null $callback [optional] 

* The autoload function being registered. * If no parameter is provided, then the default implementation of * spl_autoload will be registered. *

* @param bool $throw This parameter specifies whether spl_autoload_register() should throw exceptions when the * autoload_function cannot be registered. Ignored since since 8.0. * @param bool $prepend If true, spl_autoload_register() will prepend the autoloader on the autoload stack instead of * appending it. * @return bool true on success or false on failure. * @throws TypeError Since 8.0. * @since 5.1.2 */
function spl_autoload_register(?callable $callback, bool $throw = true, bool $prepend = false): bool { }

举例说明(一)


function

你可能感兴趣的:(php,android,开发语言,linux,nginx,java,python)