class Manage
{

spl_autoload_register(function($class) {
    include $class . '.class.php';
});
}

Say I have some code like the above. I chose to use the anonymous function method of loading classes, but how is this used? How exactly does it determine which '$class' to load?

说我有一些像上面这样的代码。我选择使用加载类的匿名函数方法,但这是如何使用的?它究竟是如何确定加载哪个'$ class'的?

2 个解决方案

#1


22

You can't put the code there. You should add the SPL register after your class. If you wanted to register a function inside the Manage class you could do:

你不能把代码放在那里。你应该在课后添加SPL寄存器。如果你想在Manage类中注册一个函数,你可以这样做:

class Manage {
    public static function autoload($class) {
        include $class . '.class.php';
    }
}

spl_autoload_register(array('Manage', 'autoload'));

However, as you demonstrated you can use an anonymous function. You don't even need a class, so you can just do:

但是,正如您演示的那样,您可以使用匿名函数。你甚至不需要课程,所以你可以这样做:

spl_autoload_register(function($class) {
    include $class . '.class.php';
});

Either way, the function you specify is added to a pool of functions that are responsible for autoloading. Your function is appended to this list (so if there were any in the list already, yours will be last). With this, when you do something like this:

无论哪种方式,您指定的函数都会添加到负责自动加载的函数池中。您的功能将附加到此列表中(因此,如果列表中已有任何功能,则您的功能将是最后一个)。有了这个,当你做这样的事情时:

UnloadedClass::someFunc('stuff');

PHP will realize that UnloadedClass hasn't been declared yet. It will then iterate through the SPL autoload function list. It will call each function with one argument: 'UnloadedClass'. Then after each function is called, it checks if the class exists yet. If it doesn't it continues until it reaches the end of the list. If the class is never loaded, you will get a fatal error telling you that the class doesn't exist.

PHP将意识到尚​​未声明UnloadedClass。然后它将遍历SPL自动加载功能列表。它将使用一个参数调用每个函数:'UnloadedClass'。然后在调用每个函数之后,它会检查该类是否存在。如果没有,它会继续,直到它到达列表的末尾。如果从未加载该类,您将收到一个致命错误,告诉您该类不存在。

更多相关文章

  1. 如何让jQuery ajax执行错误功能
  2. php变量函数,回调函数
  3. PHP里为啥会有session_start()这个函数?
  4. PHP - 函数 & 检测函数/类/方法是否存在
  5. 如何在表单操作中执行PHP函数?
  6. 使用jquery / ajax在CodeIgniter控制器内调用函数
  7. php数字操作,高精度函数,保留计算结果小数位
  8. php之简单的文件管理(基本功能)
  9. 函数不返回“functions.php”中的值

随机推荐

  1. Android 允许权限
  2. android中文字跑马灯效果
  3. Android日期时间格式国际化
  4. android 颜色值 xml
  5. Android Property System
  6. 【Android UI】色板
  7. AndroidщАЪш┐ЗViewPagerхоЮчО
  8. 在eclipse中查看Android(安卓)SDK源代码
  9. 2013.10.14 “?android ”
  10. 默认的Android(安卓)Dialog 样式