spl_autoload_register 混淆要求
spl_autoload_register confusion on require
所以我已经阅读了这个 PHP
函数的一些内容,并且我了解如何实例化它,尽管我在理解用例和 spl_autoload_register
函数的功能方面可能存在困难。这就是我所拥有的
<?php
spl_autoload_register(function($class){
require_once "classes/{$class}.php";
});
但我的问题是我的 classes
目录是否像这样
-Security.php
-Zipper.php
-Functions.php
-Sanitize.php
-Extract.php
如果我的页面不需要其中的每一个,它实际上 require
类 吗?还是只在 require
这样调用时才
new Zipper;
请帮我澄清一下 spl_autoload_register
函数的混淆。
命名约定也有效吗?假设我尝试实例化 new Hashing;
并且它属于 Security.php
它究竟如何知道如何 require
那个文件,或者像我说的命名约定有帮助吗?
例子
<?php
spl_autoload_register(function($class){
switch($class) {
case "Booger":
case "booger": $class = "Snot";
}
require_once "classes/{$class}.php";
});
spl_autoload_register
将只允许 class 到 可能 可用而不是出错——它实际上并没有实例化 class.
您在回调中做什么由您决定。您的 "Security.php" class 文件应该类似于:
class Security {
[...]
}
无论您包含什么文件,例如 require_once "classes/{$class}.php";
表示文件中的文件名和 class 名称必须匹配 $class
.
每当您启动内存中不可用的 class 时,都会调用 spl_autoload_register
。如果 class 尚未加载,它会告诉引擎去哪里寻找 class,这确实是一个安全网。所以只有当你在脚本中第一次使用class时才会包含某个文件。
您可以编写关于要包含哪个文件的条件语句,但这不是使用该方法的一种非常干净的方式。
最有用的用例是通过特定的命名约定为每个 class 创建一个文件。这使您和其他人以后更容易在您的项目中找到 class。
所以我已经阅读了这个 PHP
函数的一些内容,并且我了解如何实例化它,尽管我在理解用例和 spl_autoload_register
函数的功能方面可能存在困难。这就是我所拥有的
<?php
spl_autoload_register(function($class){
require_once "classes/{$class}.php";
});
但我的问题是我的 classes
目录是否像这样
-Security.php
-Zipper.php
-Functions.php
-Sanitize.php
-Extract.php
如果我的页面不需要其中的每一个,它实际上 require
类 吗?还是只在 require
这样调用时才
new Zipper;
请帮我澄清一下 spl_autoload_register
函数的混淆。
命名约定也有效吗?假设我尝试实例化 new Hashing;
并且它属于 Security.php
它究竟如何知道如何 require
那个文件,或者像我说的命名约定有帮助吗?
例子
<?php
spl_autoload_register(function($class){
switch($class) {
case "Booger":
case "booger": $class = "Snot";
}
require_once "classes/{$class}.php";
});
spl_autoload_register
将只允许 class 到 可能 可用而不是出错——它实际上并没有实例化 class.
您在回调中做什么由您决定。您的 "Security.php" class 文件应该类似于:
class Security {
[...]
}
无论您包含什么文件,例如 require_once "classes/{$class}.php";
表示文件中的文件名和 class 名称必须匹配 $class
.
spl_autoload_register
。如果 class 尚未加载,它会告诉引擎去哪里寻找 class,这确实是一个安全网。所以只有当你在脚本中第一次使用class时才会包含某个文件。
您可以编写关于要包含哪个文件的条件语句,但这不是使用该方法的一种非常干净的方式。
最有用的用例是通过特定的命名约定为每个 class 创建一个文件。这使您和其他人以后更容易在您的项目中找到 class。