Function __autoload Has Been Removed in PHP 8.0

Autoloading is a process to automatically load classes and interfaces without using include, include_once, require, or require_once statements at the beginning on each PHP file. The __autoload is a function that can be defined to enable classes and interfaces autoloading. This function is automatically called when class or interface is currently not defined.

Since PHP 7.2, __autoload has been deprecated and since PHP 8.0 this function has been removed. Instead of __autoload function we need to use spl_autoload_register function. This function is more flexible because it allows to specify many autoloaders.

Let’s say we have a User class:

User.php

<?php

class User {}

We have defined the __autoload function for autoloading classes and interfaces:

<?php

function __autoload(string $name) {
    require_once $name.'.php';
}

$user = new User();

A code can be rewritten using spl_autoload_register function as follows:

<?php

function autoloader(string $name) {
    require_once $name.'.php';
}

spl_autoload_register('autoloader');

$user = new User();

Leave a Comment

Your email address will not be published. Required fields are marked *