简体   繁体   English

通过仅将文件放入PSR-4目录来加载PHP类

[英]Loading PHP classes by just putting files into PSR-4 directory

In my current lib, I have classes with static code outside the class definition, that I would like to execute when browsing a index.php file that has autoloading (with properly putting the class files into a PSR-4 folder structure, and calling composer install before). 在我当前的lib中,我有一些类带有静态代码,这些类具有超出类定义的静态代码,当我浏览具有自动加载功能的index.php文件(将类文件正确放入PSR-4文件夹结构,并调用composer install时)时,希望执行composer install之前)。

It's not such a bad deal. 这不是什么坏事。 For instance, in my custom Error.php class I could for instance call set_error_handler function outside the class so warnings could be catchable. 例如,在我的自定义Error.php类中,我可以在该类之外调用set_error_handler函数,以便可以捕获警告。 And putting this file in a PSR-4 autoloading could ease the pain for not having to call any Error.php code in index.php to enable this catching. 将该文件放入PSR-4自动加载程序可以减轻不必在index.php调用任何Error.php代码来启用此捕获的Error.php Every source that just uses my namespace and autoloads my lib would have that for granted. 每个仅使用我的命名空间并自动加载我的库的源都将被视为理所当然。

I tried to include use \\MyNamespace\\Error; 我试图包括use \\MyNamespace\\Error; in the index.php file, but the code in Error.php , outside the Error class definition, isn't automatically executed. index.php文件中,但是不会自动执行Error类定义之外的Error.php的代码。

The code outside the class is only executed when I call a class method inside my index.php file (the one that has the autoloading) . 仅当我在index.php文件(具有自动加载功能)中调用类方法时,才执行类外部的代码。

Can this be done ? 能做到吗? Thanks for your time. 谢谢你的时间。

use \\MyNamespace\\Error; does not trigger autoloading, it just allows you to use shorter class name in code - new Error() instead of new \\MyNamespace\\Error() . 不会触发自动加载,它只允许您在代码中使用较短的类名new \\MyNamespace\\Error() new Error()而不是new \\MyNamespace\\Error() If you want to include Error.php file, you need to use this class. 如果要包含Error.php文件,则需要使用此类。 Probably the safest way would to use class_exist() : 可能最安全的方法是使用class_exist()

class_exists(Error::class);

But honestly you should rethink your design, implicit registering error handler in file with class declaration is against PSR-1 and may be really annoying in big project. 但老实说,您应该重新考虑您的设计,使用类声明在文件中隐式注册错误处理程序是针对PSR-1的 ,在大型项目中可能确实很烦人。

Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (eg generate output, change .ini settings, etc.) but SHOULD NOT do both 文件应该声明符号(类,函数,常量等)或引起副作用(例如,生成输出,更改.ini设置等),但不应两者都做

https://www.php-fig.org/psr/psr-1/#23-side-effects https://www.php-fig.org/psr/psr-1/#23-side-effects

It would be less magical if you create separate method for registering error handler and call it explicitly in index.php : 如果您创建用于注册错误处理程序的单独方法并在index.php显式调用它,那么它的魔力就会减少:

Error::registerErrorHandler();

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

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