Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : What is the benefit of spl_autoload_register? Performance of includes

I've been reading about spl_autoload_register functions as a substitution of require, require_once, include, & include_once. Although there is much discussion about how to implement this, the documentation isn't too detailed and there isn't an explaination as to how it would be beneficial vs the original ways.

Reference : http://php.net/manual/en/function.spl-autoload-register.php

I am wondering how spl_autoload_register works?

Is there a performance difference when using spl_autoload_register?

How does it handle many require statements (more than 20) in cross linked classes? (Wouldn't this still result in duplicate requires?)

like image 439
mlishn Avatar asked Aug 06 '12 16:08

mlishn


1 Answers

I haven't ever tested (nor worried about) performance, but I always use an autoloader, because it makes your life sooo much easier.

For an implementation see: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

What happens is that when you try to access a class e.g. Foo of which the file isn't loaded yet. The autoloader will kick in and tries to load the file belonging to the class.

This can be easily done by "correctly" organizing the files in your project. Lets say you have a class \Project\Http\Client (or the "old style" non namespaced Project_Http_Client) it will try to load the file: Project/Http/Client.php.

like image 171
PeeHaa Avatar answered Oct 10 '22 16:10

PeeHaa