Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use spl_autoload() instead of __autoload()

According to http://php.net/manual/en/language.oop5.autoload.php the magic function __autoload() was deprecated as of PHP 7.2.0 and removed as of PHP 8.0.0.

The official alternative is spl_autoload(). See http://www.php.net/manual/en/function.spl-autoload.php. But the PHP manual does not explain the proper use of this baby.

My question: How to replace this (my automatic class autoloader) with a version with spl_autoload()?

function __autoload($class) {     include 'classes/' . $class . '.class.php'; } 

Problem: I cannot figure out how to give that function a path (it only accepts namespaces).

By the way, there are a lot of threads regarding this topic here on SO, but none gives a clean & simple solution that replaces my sexy one-liner.

like image 361
Sliq Avatar asked May 21 '12 15:05

Sliq


People also ask

What does the function spl_autoload_register do in PHP?

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared.

How do you autoload in PHP?

The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

What is autoloading explain with example?

What is autoloader. An autoloader is a function that takes a class name as an argument and then includes the file that contains the corresponding class, for example: function autoloader ( $class ) { $path = $DOCUMENT_ROOT . '/ classes/'; require $path . $ class .'.


1 Answers

You need to register autoload functions with spl_autoload_register. You need to provide a "callable". The nicest way of doing this, from 5.3 onwards, is with an anonymous function:

spl_autoload_register(function($class) {     include 'classes/' . $class . '.class.php'; }); 

The principal advantage of this against __autoload is of course that you can call spl_autoload_register multiple times, whereas __autoload (like any function) can only be defined once. If you have modular code, this would be a significant drawback.


2018 update to this: there shouldn't really be that many occasions when you need to roll your own autoloader. There is a widely accepted standard (called PSR-4) and several conforming implementations. The obvious way of doing this is using Composer.

like image 165
lonesomeday Avatar answered Sep 22 '22 21:09

lonesomeday