Is PHP 5 autoload inefficient?

When you manually include the PHP class, you can do this while the current script is running, right? Then you can decide if the condition matches you, download it, and if not, you wonโ€™t. Like this:

if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { include '../../../Whatever/SanitizeUserInput.class.php'; SanitizeUserInput::sanitize($_POST['someFieldName']); } 

But let's say I use autoload with this class. Will it be loaded effectively at the beginning, or will it be loaded only if used?

I want to say whether I should add the __autoload function only in classes on which I am 100% sure that I will use in any script (for example, connecting to a database, managing session, etc.)?

thanks

+4
source share
3 answers

Startup is only called when you try to access the required class. And it would be better to use spl_autoload_register() instead of __autoload

Documentation:

You can define the __autoload () function, which is automatically called if you try to use a class / interface that has not yet been defined.

and

spl_autoload_register () provides a more flexible alternative for autoload classes. For this reason, the use of __autoload () is discouraged and may be outdated or removed in the future.

+6
source

Startup starts when you try to use a class that is not loaded yet:

 include 'foo.php'; new Foo; // autoload not used, because the class already exists // Bar is not yet loaded here, auto or otherwise new Bar; // Bar is being autoloaded, because it was not yet loaded 

Thus, autoload can be very efficient. This is slightly less efficient than manually loading classes at the time you need them, due to the overhead of invoking the autoload function. But keeping track of loaded classes manually is a lot of work for a very small return to startup.

+4
source

Try it, you will see that whenever PHP stumbles upon a class, it does not know yet, it will call your autoload function. When your autoload function tells PHP which file the class is in, it will load that file.

To make the answer short, PHP only downloads the file, if necessary, this is true even for conditions, so the next test class will never be loaded.

 if (false) { $test = new CTest(); // never loaded with autoload. } 
+2
source

Source: https://habr.com/ru/post/1400170/


All Articles