Function __autoload Has Been Removed in PHP 8.0

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 of each PHP file. The __autoload is a function that can be defined to enable classes and interfaces autoloading. This function is automatically called when a 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 the __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 the spl_autoload_register function as follows:

<?php

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

spl_autoload_register('autoloader');

$user = new User();

The 1 Comment Found

Leave a Comment

Cancel reply

Your email address will not be published.