Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is PHP 5's autoload inefficient?

When you manually include a PHP class you can do it while the current script is running, right? Then you can decide, if a condition matches you load it and if it doesn't you don't. Like this:

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

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

I mean, should I add the __autoload function only in classes that I'm 100% sure I'm going to use in any script (e.g. database connection, session management, etc.)?

Thanks

like image 611
federico-t Avatar asked Dec 16 '22 03:12

federico-t


1 Answers

Autoload is called only when you are trying to access desired class. And it would be better to use spl_autoload_register() instead of __autoload

Documentation:

You may define an __autoload() function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet.

and

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

like image 96
Timur Avatar answered Dec 28 '22 14:12

Timur