The spl_autoload_register() https://www.php.net/manual/en/function.spl-autoload-register.php函数是让事情井井有条的便捷方法。您可以根据需要使用它来加载静态类方法,方法是将其放在'init.php'文件,您在每个脚本的顶部都需要该文件。下面是一个 Hash 类的示例,其中包含创建盐和哈希的静态方法:
<?php
require_once('init.php');
$salt = Hash::salt(32);
$pw = Hash::make($_POST['password'], $salt);
?>
与init.php and 类/Hash.php文件看起来如下所示:
初始化.php:
<?php
spl_autoload_register(function($class) {
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/' . $class . '.php';
});
?>
哈希.php:
<?php
class Hash {
public static function make($string, $salt = '') {
return hash('sha256', $string . $salt);
}
public static function salt($length) {
return base64_encode(openssl_random_pseudo_bytes($length));
}
}
?>
The spl_autoload_register()
当函数在代码中第一次遇到实例化或静态方法的使用时,它会根据您作为参数提供的函数找到适当的类。
您可以通过将相关函数分组为静态方法来利用这一点。例如,我的classes特定项目的目录有:
Config.php Cookie.php DB.php
Err.php FormatError.php Hash.php
Input.php MismatchError.php Redirect.php
RequiredFieldError.php Session.php StringLengthError.php
Token.php UniqueItemError.php User.php
Validate.php
其中包含彼此相关的静态方法等。仅当 Php 在包含 init.php 文件的任何脚本中的任何位置遇到它们的名称时,它们才会被加载。