简体   繁体   English

使用spl_autoload_register

[英]Using spl_autoload_register

Must I put the following lines in each PHP file I create to use autoloader? 我必须在创建的每个PHP文件中放入以下行以使用自动加载器吗? Or there is a solution to do it once, inside "index.php" of the application for example, and instantiate the classes in other files like usual? 还是有一种解决方案,例如在应用程序的“ index.php”内部执行一次,然后像往常一样实例化其他文件中的类?

function autoload($class) {

    require('/path/to/mylibrary/' . str_replace('_', '/', $class) . '.php');
}

spl_autoload_register('autoload');

Thanks. 谢谢。

You add these lines once. 您添加这些行一次。 The rest of the request your autoload-function will be used to load the class-files. 请求的其余部分将使用autoload-function来加载类文件。 You should put this somewhere at the start of your php, for example in the index.php. 您应该将其放在php的开头,例如在index.php中。 But if you have multiple entry-points (for example http://www.example.com/index.php and http://www.example.com/page.php ) all these files should have the spl_autoload_register (either via copy-paste but more preferable via an include(..) ). 但是,如果您有多个入口点(例如http://www.example.com/index.phphttp://www.example.com/page.php ),则所有这些文件都应具有spl_autoload_register (可以通过复制-paste,但更可取的是通过include(..) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM