PHP自动加载的原理是什么? [英] What's the principle of autoloading in PHP?

查看:166
本文介绍了PHP自动加载的原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

spl_autoload_register可以完成这种工作,但是我不知道这种工作是如何完成的?

spl_autoload_register can do this kind of job,but I don't understand how is that kind of job done?

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

推荐答案

基本思想是,您不再需要编写include/require指令:每当您尝试使用未定义的指令时类,PHP将调用自动加载器.

The basic idea is that you don't have to write include/require instructions anymore : whenever you're trying to use a non-defined class, PHP will call the autoloader.

然后,自动加载器的工作是确定应该加载哪个文件,然后include确定要加载的文件.

The job of the autoloader, then, is to determine which file should be loaded, and include it, so the class becomes defined.

PHP可以使用该类,就像您是编写include指令的类一样,该类实际上已经在自动加载功能中执行了.

PHP can then use that class, as if you were the one who wrote the include instruction, that has in fact been executed in the autoloading function.


窍门"是自动加载功能:


The "trick" is that the autoloading function :

  • 仅接收类的名称
  • 必须确定要加载的文件-即哪个文件包含该类.

这是命名约定的原因,例如PEAR,它表示将诸如Project_SubProject_Component_Name的类映射到诸如Project/SubProject/Component/Name.php的文件-即,类名中的'_'被替换为在文件系统上将(目录,子目录)斜杠.

This is the reason for naming convention, such as the PEAR one, which says that class such as Project_SubProject_Component_Name are mapped to files such as Project/SubProject/Component/Name.php -- i.e. '_' in the class names are replaces by slashes (directories, subdirectories) on the filesystem.


例如,如果您查看Doctrine_Core::autoload方法,该方法在您的情况下将被称为自动加载器,则其中包含代码的这一部分(在处理某些特定情况之后):


For instance, if you take a look at the Doctrine_Core::autoload method, which is the one that will be called as an autoloader in your case, it contains this portion of code (after dealing with some specific cases) :

$class = self::getPath() 
            . DIRECTORY_SEPARATOR . 
            str_replace('_', DIRECTORY_SEPARATOR, $className) 
            . '.php';
if (file_exists($class)) {
    require $class;
    return true;
}
return false;

这意味着将类名映射到文件系统,用'/'替换'_',并在文件名中添加最后一个.php.

Which means the class name's is mapped to the filesystem, replacing '_' by '/', and adding a final .php to the file name.

例如,如果您尝试使用Doctrine_Query_Filter_Chain类,而PHP不知道该类,则将调用Doctrine_Core::autoload函数;它将确定应加载的文件为Doctrine/Query/Filter/Chain.php;并且在该文件存在的情况下将包含该文件-这意味着PHP现在知道" Doctrine_Query_Filter_Chain类.

For instance, if you're trying to use the Doctrine_Query_Filter_Chain class, and it is not known by PHP, the Doctrine_Core::autoload function will be called ; it'll determine that the file that should be loaded is Doctrine/Query/Filter/Chain.php ; and as that file exists, it'll be included -- which means PHP now "knows" the Doctrine_Query_Filter_Chain class.

这篇关于PHP自动加载的原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆