Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php spl_autoload_register vs __autoload?

Tags:

php

autoload

hello is there any diffrence useing this excepts that we can use our own name auto load? is there any performance difference? how do they internally work?

between

function __autoload_libraries($class){     include_once 'lib.'.$class.'.php'; }  spl_autoload_register('__autoload_libraries'); 

vs

function __autoload($class){     include_once 'lib.'.$class.'.php'; } 
like image 579
Adam Ramadhan Avatar asked Aug 01 '11 05:08

Adam Ramadhan


2 Answers

__autoload is generally considered obsolete. It only allows for a single autoloader. Generally you should only use __autoload if you're using a version of PHP without support for spl_autload_register.

spl_autoload_register allows several autoloaders to be registered which will be run through in turn until a matching class/interface/trait is found and loaded, or until all autoloading options have been exhausted. This means that if you're using framework code or other third party libraries that implement their own autoloaders you don't have to worry about yours causing conflicts.

UPDATE:

__autoload is now officially deprecated as of PHP 7.2.0, which means it's now on the chopping block. If you want your code to be compatible with future versions of PHP you definitely should not use __autoload

like image 183
GordonM Avatar answered Sep 22 '22 13:09

GordonM


Documentation for "Autoloading Classes" reads:

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.

Documentation for spl_autoload_register() reads:

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

like image 25
Vladimir Kornea Avatar answered Sep 22 '22 13:09

Vladimir Kornea