简体   繁体   中英

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).

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. 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. Every source that just uses my namespace and autoloads my lib would have that for granted.

I tried to include use \\MyNamespace\\Error; in the index.php file, but the code in Error.php , outside the Error class definition, isn't automatically executed.

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) .

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() . If you want to include Error.php file, you need to use this class. Probably the safest way would to use 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.

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

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 :

Error::registerErrorHandler();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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