phpday 2027 - Call for Papers

Caricamento automatico delle Classi

Molti sviluppatori che producono applicazioni orientate agli oggetti creano un file sorgente PHP per ogni classe definita. Uno dei più grossi inconvenienti è la necessità di scrivere una lunga lista di inclusioni necessarie all'inizio di ogni script (un'inclusione per ogni classe).

La funzione spl_autoload_register() registra un numero qualsiasi di autoloader, permettendo a classi e interfacce di essere caricate automaticamente se non sono attualmente definite. Registrando degli autoloader, PHP ha un'ultima possibilità di caricare la classe o l'interfaccia prima di fallire con un errore.

Qualsiasi costrutto simile a una classe può essere caricato automaticamente allo stesso modo. Questo include classi, interfacce, trait ed enumerazioni.

Attenzione

Prima di PHP 8.0.0, era possibile usare __autoload() per caricare automaticamente classi e interfacce. Tuttavia, è un'alternativa meno flessibile rispetto a spl_autoload_register() e __autoload() è deprecata a partire da PHP 7.2.0, e rimossa a partire da PHP 8.0.0.

Nota:

spl_autoload_register() può essere chiamata più volte per registrare più autoloader. Tuttavia, lanciare un'eccezione da una funzione di autoload interromperà quel processo e non permetterà l'esecuzione di ulteriori funzioni di autoload. Per questo motivo, lanciare eccezioni da una funzione di autoload è fortemente sconsigliato.

Example #1 Esempio di autocaricamento

Questo esempio cerca di caricare le classi MyClass1 e MyClass2 rispettivamente dai file MyClass1.php e MyClass2.php.

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

Example #2 Altro esempio di autocaricamento

Questo esempio tenta di caricare l'interfaccia ITest.

<?php

spl_autoload_register(function ($name) {
    var_dump($name);
});

class Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

Example #3 Utilizzo dell'autoloader di Composer

» Composer genera un file vendor/autoload.php configurato per caricare automaticamente i pacchetti gestiti da Composer. Includendo questo file, tali pacchetti possono essere usati senza alcun lavoro aggiuntivo.

<?php
require __DIR__ . '/vendor/autoload.php';

$uuid = Ramsey\Uuid\Uuid::uuid7();

echo "Generato nuovo UUID -> ", $uuid->toString(), "\n";
?>

User Contributed Notes 5 notes

up
107
jarret dot minkler at gmail dot com
17 years ago
You should not have to use require_once inside the autoloader, as if the class is not found it wouldn't be trying to look for it by using the autoloader. 

Just use require(), which will be better on performance as well as it does not have to check if it is unique.
up
64
str at maphpia dot com
10 years ago
This is my autoloader for my PSR-4 clases. I prefer to use composer's autoloader, but this works for legacy projects that can't use composer.

<?php
/**
 * Simple autoloader, so we don't need Composer just for this.
 */
class Autoloader
{
    public static function register()
    {
        spl_autoload_register(function ($class) {
            $file = str_replace('\\', DIRECTORY_SEPARATOR, $class).'.php';
            if (file_exists($file)) {
                require $file;
                return true;
            }
            return false;
        });
    }
}
Autoloader::register();
up
36
toi]n[enkayt[attaat]gmaal.com
6 years ago
Autoloading plain functions is not supported by PHP at the time of writing. There is however a simple way to trick the autoloader to do this. The only thing that is needed is that the autoloader finds the searched class (or any other autoloadable piece of code) from the files it goes through and the whole file will be included to the runtime.

Let's say you have a namespaced file for functions you wish to autoload. Simply adding a class of the same name to that file with a single constant property is enough to trigger the autoloader to seek for the file. Autoloading can then be triggered by accessing the constant property.

The constant could be replaced by any static property or method or by default constructor. However, I personally find a constant named 'load' elegant and informative. After all this is a workaround. Another thing to keep in mind is that this introduces an unnecessary class to the runtime. The benefit of this is that there is no need to manually include or require files containing functions by path which in turn makes code maintaining easier. Such behaviour makes it easier to alter the project structure since manual includes need not to be fixed. Only the autoloader needs to be able to locate the moved files which can be automated.

A code file containing functions.
/Some/Namespace/Functions.php
<?php
namespace Some\Namespace;

class Functions { const load = 1; }

function a () {
}

function b () {
}
?>

Triggering autoloading of the file containing functions.
main.php
<?php
\Some\Namespace\Functions::load;

a ();
b ();
?>
up
22
Anonymous
16 years ago
It's worth to mention, if your operating system is case-sensitive you need to name your file with same case as in source code eg. MyClass.php instead of myclass.php
up
4
kalkamar at web dot de
18 years ago
Because static classes have no constructor I use this to initialize such classes.
The function init will (if available) be called when you first use the class.
The class must not be included before, otherwise the init-function wont be called as autoloading is not used.

<?php
function __autoload($class_name)
{
    require_once(CLASSES_PATH.$class_name.'.cls.php');
    if(method_exists($class_name,'init'))
        call_user_func(array($class_name,'init'));
    return true;
}
?>

I use it for example to establish the mysql-connection on demand.

It is also possilbe do add a destructor by adding this lines to the function:
<?php
if(method_exists($class_name,'destruct'))
    register_shutdown_function(array($class_name,'destruct'));
?>
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top