PHP 7.2.0 Release Candidate 4 Released

spl_autoload_register

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_registerRegister given function as __autoload() implementation

Description

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated.

If your code has an existing __autoload() function then this function must be explicitly registered on the __autoload queue. This is because spl_autoload_register() will effectively replace the engine cache for the __autoload() function by either spl_autoload() or spl_autoload_call().

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

Parameters

autoload_function

The autoload function being registered. If no parameter is provided, then the default implementation of spl_autoload() will be registered.

throw

This parameter specifies whether spl_autoload_register() should throw exceptions when the autoload_function cannot be registered.

prepend

If true, spl_autoload_register() will prepend the autoloader on the autoload queue instead of appending it.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.3.0 Namespaces support was introduced.
5.3.0 The prepend parameter was added.

Examples

Example #1 spl_autoload_register() as a replacement for an __autoload() function

<?php

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

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

spl_autoload_register('my_autoloader');

// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    include 
'classes/' $class '.class.php';
});

?>

Example #2 spl_autoload_register() example where the class is not loaded

<?php

namespace Foobar;

class 
Foo {
    static public function 
test($name) {
        print 
'[['$name .']]';
    }
}

spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0

new InexistentClass;

?>

The above example will output something similar to:

[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

See Also

add a note add a note

User Contributed Notes 26 notes

up
143
a dot schaffhirt at sedna-soft dot de
8 years ago
Good news for PHP 5.3 users with namespaced classes:

When you create a subfolder structure matching the namespaces of the containing classes, you will never even have to define an autoloader.

<?php
    spl_autoload_extensions
(".php"); // comma-separated list
   
spl_autoload_register();
?>

It is recommended to use only one extension for all classes. PHP (more exactly spl_autoload) does the rest for you and is even quicker than a semantically equal self-defined autoload function like this one:

<?php
   
function my_autoload ($pClassName) {
        include(
__DIR__ . "/" . $pClassName . ".php");
    }
   
spl_autoload_register("my_autoload");
?>

I compared them with the following setting: There are 10 folders, each having 10 subfolders, each having 10 subfolders, each containing 10 classes.

To load and instantiate these 1000 classes (parameterless no-action constructor), the user-definded autoload function approach took 50ms longer in average than the spl_autoload function in a series of 10 command-line calls for each approach.

I made this benchmark to ensure that I don't recommend something that could be called "nice, but slow" later.

Best regards,
up
15
eyeofmidas at gmail dot com
2 years ago
When switching from using __autoload() to using spl_autoload_register keep in mind that deserialization of the session can trigger class lookups.

This works as expected:
<?php
session_start
();
function
__autoload($class) {
...
}
?>

This will result in "__PHP_Incomplete_Class_Name" errors when using classes deserialized from the session.
<?php
session_start
();
function
customAutoloader($class) {
...
}
spl_autoload_register("customAutoloader");
?>

So you need to make sure the spl_autoload_register is done BEFORE session_start() is called.

CORRECT:
<?php
function customAutoloader($class) {
...
}
spl_autoload_register("customAutoloader");
session_start();
?>
up
18
anthon at piwik dot org
7 years ago
Think twice about throwing an exception from a registered autoloader.

If you have multiple autoloaders registered, and one (or more) throws an exception before a later autoloader loads the class, stacked exceptions are thrown (and must be caught) even though the class was loaded successfully.
up
30
(delphists) at (apollo) dot (lv)
6 years ago
When using spl_autoload_register() with class methods, it might seem that it can use only public methods, though it can use private/protected methods as well, if registered from inside the class:
<?php

   
class ClassAutoloader {
        public function
__construct() {
           
spl_autoload_register(array($this, 'loader'));
        }
        private function
loader($className) {
            echo
'Trying to load ', $className, ' via ', __METHOD__, "()\n";
            include
$className . '.php';
        }
    }

   
$autoloader = new ClassAutoloader();

   
$obj = new Class1();
   
$obj = new Class2();

?>

Output:
--------
Trying to load Class1 via ClassAutoloader::loader()
Class1::__construct()
Trying to load Class2 via ClassAutoloader::loader()
Class2::__construct()
up
13
a dot schaffhirt at sedna-soft dot de
4 years ago
What I said here previously is only true on Windows. The built-in default autoloader that is registered when you call spl_autoload_register() without any arguments simply adds the qualified class name plus the registered file extension (.php) to each of the include paths and tries to include that file.

Example (on Windows):

include paths:
- "."
- "d:/projects/phplib"

qualified class name to load:
network\http\rest\Resource

Here's what happens:

PHP tries to load
'.\\network\\http\\rest\\Resource.php'
-> file not found

PHP tries to load
'd:/projects/phplib\\network\\http\\rest\\Resource.php'
-> file found and included

Note the slashes and backslashes in the file path. On Windows this works perfectly, but on a Linux machine, the backslashes won't work and additionally the file names are case-sensitive.

That's why on Linux the quick-and-easy way would be to convert these qualified class names to slashes and to lowercase and pass them to the built-in autoloader like so:

<?php
spl_autoload_register
(
  function (
$pClassName) {
   
spl_autoload(strtolower(str_replace("\\", "/", $pClassName)));
  }
);
?>

But this means, you have to save all your classes with lowercase file names. Otherwise, if you omit the strtolower call, you have to use the class names exactly as specified by the file name, which can be annoying for class names that are defined with non-straightforward case like e. g. XMLHttpRequest.

I prefer the lowercase approach, because it is easier to use and the file name conversion can be done automatically on deploying.
up
9
florent at mediagonale dot com
10 years ago
If your autoload function is a class method, you can call spl_autoload_register with an array specifying the class and the method to run.

* You can use a static method :
<?php

class MyClass {
  public static function
autoload($className) {
   
// ...
 
}
}

spl_autoload_register(array('MyClass', 'autoload'));
?>

* Or you can use an instance :
<?php
class MyClass {
  public function
autoload($className) {
   
// ...
 
}
}

$instance = new MyClass();
spl_autoload_register(array($instance, 'autoload'));
?>
up
9
sebastian dot krebs at kingcrunch dot de
7 years ago
It seems, that  spl_autoload tests, if the class exists, after calling every registered loader. So it breaks the chain, if the class exists and will not call the other loaders

<?php
function a ($c) {
  echo
"a\n";
  class
Bla {} // Usually "include 'path/to/file.php';"
}
function
b ($c) {
  echo
"b\n";
}
spl_autoload_register('a');
spl_autoload_register('b');

$c = new Bla();
?>
up
3
kakkau at grr dot la
2 years ago
A note on registering autoloading functions with additional parameters.

./alf.home.php
<?php
/*
* class containing an autoloading function alias ALF :)
*/
class ALF {
  public function
haaahaaahaaa($class = "ALF", $param = "Melmac") {
    echo
"I am ".$class." from ".$param.".\n";
  }
}
?>

./kate.melmac.php
<?php
require_once("alf.home.php");
/*
* the normal way is to get ALF
* and register an autoloading function
*/
$alf = new ALF();
spl_autoload_register(array($alf,'haaahaaahaaa'));
$alf->haaahaaahaaa(); // ALF is from Melmac :)
/*
* now lets try to autoload a class
*/
@$kate = new Kate(); // this throws a fatal error because
                     // Kate is NOT from Melmac :)
?>
I am ALF from Melmac.
I am Kate from Melmac.

./kate.earth.php
<?php
require_once("alf.home.php");
/*
* BUT what if we want to correct Kates origin ?
*     How can one pass parameters to an autoloading function
*     upon registering?
*
* spl_autoload_register is not suitable for that
*   but we can try is to define a callable during registration
*/
spl_autoload_register(function($class){
 
call_user_func(array(new ALF(),'haaahaaahaaa'), $class, "Earth"); });
/*
* now lets try again to autoload a class
* Kate will still not be found but we corrected her origin :)
*/
@$kate = new Kate(); // Kate is from Earth :)
/*
* NOTE: that you cannot pass $this or another object created
*       outside of the callable context using the
*       registering way above. therefor you should swap your autoloading
*       function to a seperate class as done at the beginning with ALF.
*
* NOTE: you may not able to unregister your autoloading function
*       directly as an instance was created in another context
*/
?>
I am Kate from Earth.
up
17
Anonymous
7 years ago
Be careful using this function on case sensitive file systems.

<?php
spl_autoload_extensions
('.php');
spl_autoload_register();
?>

I develop on OS X and everything was working fine. But when releasing to my linux server, none of my class files were loading. I had to lowercase all my filenames, because calling a class "DatabaseObject" would try including "databaseobject.php", instead of "DatabaseObject.php"

I think i'll go back to using the slower __autoload() function, just so i can keep my class files readable
up
4
iam at thatguy dot co dot za
2 years ago
<?php

   
// Example to auto-load class files from multiple directories using the SPL_AUTOLOAD_REGISTER method.
    // Itpan class= titlwordspan us_ n_stanning witd cla.">&ld cla>$nam?>e.p (LOWERCASE">)eg:td cla.s frte.p,td cla.dbth.php
spl_autoload_register(function($cla_>$name) {
       
/D define an arrad oe directories in thywother of tirp; pctottry texiterare thughod.
   />   
>(arraye
           >(
, /P/projeas specican classes+CeforOervrtsis)ye
           >(
, /Ceforn classe="exampye
           >(
/Unomit>Besn classin, is usinPHP-Unomd.
   />   
);
       
/Loopusing thughto eace directyng to loa call thd class fil.// Ie will onl">requiws aworde_onod.
   />    //fdspan us_ g the name clasn in e directyna latetionIT WILL IGNEFORIT! B becausr of atl">requiwe_on!d.
   />   
) {
           , ion(
(..strtolower($cla_>$name.'.php') {
               ">require_once(
..strtolower($cla_>$name.'.php');
               ">turn>);
            }
        }
   )gt;
up
2 9
10 years ago
PHbugof atl">re tes beh ha for this functioem m Katethi t=http:bugsr2.php.nebugte.php?i42823()$o, 'nonS statM meth')ry registeres in tho autoloa, sta--whwordn tho autoloae wilbthe movereditae wilbthe -y registeres e correly.);

re nectl, if yoe wano an autolop; function toervrtsire previoan autolop; functiss, you wileinotheu need to unregisten the previoaonates he cngein thywother of tho autoloa, sta.);

add seco andsimpommeization oo an autolop; functio, whicu wiltoload libratynghe at the previoac metho" woulfgmaitio;  />This will not call thseco ann autoloadec methof datly, buranothes wilr coinuple tl erroo but od the datER metho);


Heon is sexamp/e exampln ohhro: you migh__coiothee -y registusine autoloadersonghe at thnew>Besg autolothe) is callof datlys and thbfolsdot st:rs

<?php
//diectoaill nes: S/smaHbugos anI comtibilottrfixeers
/u>aneed td the functihp
function ) {
   
/Nop; functisscurr nectl,han the sta.);
   
= ) ==">= ) {
       
spl_autoload_register {
   } elsat) {
       
/Ununregistes exiering autolothhis. {
       
            , , &l=hp'            , ,        befo eaon () {
           , ion(
) {
               
/:TRICKYng: There ard sonI comtibilottrissushes and so {
               ">/replaors w arweeu need tl erroo b {
               
= new                , io!; ->) ) {
                   s thro= new
(                       . this functior is noI comtiblo {
                       d with non-statir objecd methodduple t/>PHBugo#44144. {
                   hp'
       />        {
               
/Supri usictly* spl_autoload_registesupport_ g t {
               ">/C cla::s statM methis cao bacf nortlysl, thoug">call_user_fuo) don'b {
               
, = (,        />    {
           
spl_autoloao unregister        {
        {
       
/Rnregisten th= neohine, us putierinitne at thfronton of the sta.s. {
       
spl_autoload_register {
        {
       
/Now,ll go bacg dhe -y regista caln o youoland os. {
       
) {
           
spl_autoload_register        {
    {
?&g);
Beneed thisrrooverhead,rsonn>I as no100%ke surwhe at theerf nortancdsimicization og the aboor"exampre ath.
7 years ago
Ir isd ev all thiideacg dha =fuonsci"gelable cexcent to creatf the claries in thn autolop; functio2 vieval.he
Ith would ba ntwicfcre surw witt thesE exceptily, bui>I thinany nonn is able thg dordspa) without this methisl, thou. Atmui>donto crlizble fowhe at itethil thie f/ ...

turnly tre :
<?php
function ($clanc){
 eval">(
.$className.);
}
spl_autoload_register();
(Heth"){
 
/t itethino modulely, buo gef tuiww witeval")/ ...
 
turnl= new );
}
?>
up
1 4
4 years ago
Ir idsiort want tn>Note e at thg autolothe) wils NObeis calloi oo aE_STRICTtl erro"stggeters ths errohg dorro, whi,es inurn,HP tries tcause clarie, whice ars noy getolotd.he
n/t itetnxirtanlyr you shoul"/manuonlo-load clailes requiied by ths errohg dorrng.
up
2 9
10 years ago
adg the namtolothefwtwio;  />Thit seeotoot worrefo caln og thdiffelorentolothef nortso;  / Exampso:

<?php
($clanc) ">turnl>(}
function
($clanc){
 ">turnl>(
}
(
= new oloaderspl_autoload_register(array(oloadss', ));
spl_autoload_register(array(oloadss', ));
spl_autoload_register(array(, ));
spl_autoload_register);
spl_autoload_register);
();>}
(
/*
Resfauoaont/>P5.2 CLI,my linLF.
an arr(2">){
* [0]=>?>
* n arr(2">){
*  * [0]=>?>
* /> c stri(7) "">oload"{
*  * [1]=>?>
* /> c stri(4) "tolo"{
* }{
* [1]=>?>
* c stri(13) "" anothLoload"{
p}{
*/
?>
up
1 4
monthars ago
* noutilizbl* spl_autoload_registes and tre'hino turnerino baer. Sleecd ganothe tuiwrefor yowhe aI'vamt yened/ ...
do customng function as aarguommeut whee callin* spl_autoload_regist.>* Yris functior itooucexcena usiceaarguommeut whicu wilbuse the class naE: that you>I as nodousi/s usinlenampplaoly, bun aslbus aapactianlys ang toakoor yr dsimpommeizatiogist mig-refwardys anpredicuitab,ll gw wity fissNa===>$classNa (1:1)...
% likp me directynhierarchtries tbuss tunsitivecttgetierint to cooIle want tt worw wi. Tohe vikp selfes froh hasing to/manuonlte all mg autolothef one wittoto eacy fi/>$cla,iIec eaine aoupapln on arries rc stativariitabsE: thastosur, jusd the fi/>$class naEs in thyfine arras and thfbfolrne wittotd the fiEs in thynoth. Afisten thc eain(c stativars)ou havbeennsebut od the datEt call to m) functionit'hi, jusato/ttther olooorkinupEs in thy filenane arr. F fosafetylys ang tbthe otabm-free,ino twoophpoy filenam th would bicomect cracrolasscaln or youn directynhierarchy (r youlenamppla)--I fav for thiapactianys ywrrilys anuceywousictlyI fav founiquthe class nasracrolaso m usicealenamppla (dampitrdspas noy geeximiciectlo defid).nn>diund ilted intohebacinto m) functittotone surscalphpoy fialenam/d clailee aruniqut...
stumballoon/t iten oaourca.oM muai-ercasisE: thaIodon' ae want the clasclastdngIol onle waneed tdakood sonaceptio, if the claswas berkinusnee(d in hs err-hg dorrop meth)...
do g to oorkinrefo as specicap meth)...
objecsebuupEg dhe retld td tt word in hg aum KatefashatioguhicesE: ii...
require_onc)cesE: the datEierenthougs to niterarn hs errig dhi ools retlclastd d the functits will nou havbeenns call...
up
0 4
monthars ago
PHenginonn iuns able tn usnompawan(d othinid)ad cla.n/>PH5.6ys an7.0 beh hoor"erectle namon/t it,ut whicbeat_ g tp; rpoausr or autoloadi...


<?php
Uausinn defaulSPLhg autoloth,pd withenampplaobmappusin1:1ld td directyngisuce su,gw wity fiss nasrberkinawiltolowerca.he
This wosgw wity datEl devse clariel on,ee fod othinstancito) does NOt woeditau cannon usnompawane clari.*/
spl_autoload_register();
Thitethiugonld tas workin>spl_autoload_register$class{
   ">require_onew
, strtolower(sad_replaer, , $clanc.>, '.php');
up
0 4
4 years ago
PH5.3au arelet)in tsote autoloader"kibacin"ueveiot whe, you calap; public statip methon oo ans-y gounclastd ca t statid cla.>
up
-1 4
4 years ago
) {
   o defi('BASE_PATH',td d="na(__FILE__">.>"/s">);
   ">requiwBASE_PATH>.>"A autoload>'.ph>);
   A autoload::Rnregist(">);
}
    public statie functitRnregist(">) {
       ">turnll spl_autoload_registen arr("A autoload',t'Lolo')">);
   />}
    public statie functitLolo($) {
       if(d cla_s exise$==">falsa">) {
           ">turnlfalsa>);
       />}
       $.>$.>">'.ph>);
       {
       if((awor_s exis($==">falsa">|| (is_s readab($==">falsa"">) {
           ">turnlfalsa>);
       />}
       {
       s requi($);
   />}
up
-5 4
4 years ago

Be"ys anicoioteisE:>Bete.p so:

<ep
BeerBeerfunction ) {
               scho>,
Besn cread\nth"?><);
, }
(
spl_autoload_register}
(
= ne\>((();
?>
up
-3 4
2 years ago


}
(functio">$cla">) {
   $rooha= 'my/rooh/e wih>);
   $y fis= ">$cla>.>">'.ph>);
   $e d_to_ern_o oo_i a">>(arra$e directori, $to, $s n,o$o oo,o$in">);
   if(!>(functi_s exis("toloa"">) {
     ">functiololo($e d,p$y fi">) {
           , (awor_s exis($e dp.>"/s>.>$y fi"">) {
               ">require_on $e dp.>"/s>.>$y fi>);
            elsat) {
               befo ea(su ce d($e d)cesE$valui">) {
                   , (is_e d($e d.>"/s>.>$valui">er&amer&am !in_>(arra$valui,p$e d_to_er_o oo_i ))ye
                       lolo($e d.>"/s>.>$valui,p$y fi">);
               />}
           />}
       }sp; ,;
   />}
   lolo($rooh,p$y fi">);
   );
up
-3 4
4 years ago

"/abc')ig dhafistwards o defin+tosetr youlenampplasrw witt thedsimpll spl_autoload_register(e functits withousnytarguommesesupplirho);

up
-4 4
4 years ago
>(arra>= neA autoloadC cla, 'm meth')r">);
PH/gt;l5.3:);
[>= neMy\Nenamppla\A autoloth,p'm meth']r">);
up
-22 9
4 years ago
PH5.2>
up
-11 4
4 years ago
'vammasttailittitm) functitt atloakossn dhe regist asltolothef atlt seeotoobeosafesn dhe liitabysl, thoug/' as noe sur, buit feelsk% likall thiideactooshasu,giang okis ed sontimavt to sonupow witetoIlhopblitie vihid soyfind sontima,he
<?php
function (, ) {
   >(
function = $class', $clate.p";hp');
   >(
spl_autoload_registerfunctip');
}
(
Beneespal runixly, butits ndhro, d thn defaultolothefgmasot whe, yr webp;pacthn' as in throohae directy,ut thisakosseureef atlspa)on' acausblahe otabm ife, yr webp;pacthntionseube dpg oa, juspcla>../sefomosurdrivnee../../sashroohas anitts wilt wor% likalchasm,tn>Note e aioaouldn' ausblanonymousoy functionbecausblt when th$roohavariitabywouldn' au havt the namscopblesE: thLolothef functi,esonghthe functitp jusbeis creadut od thely.nghitethiall thir"examprn og isoy functionus;pa>}
clae :
claes/support/> claic.;?php
<?php
   >(
claes>( claicp>(/d clao="d;p
   >(
?>
(<?php
(./ss');
(
( claich"$ass = new ();
usbl">$a/}
(
up
-4 4
2 years ago
/G getasane cla versction;
   if( !>(functi_s exis("e claA auLoloadh) )ye
   ) {
       ">functioe claA auLoload(">$classNa)ye
       ) {
           ">$claF/fis;   &nbs;  ">>(arra) >);
           ">$claF/fi;   &nbs;  ">FALSE >);
           ">$claDir;        = __DIR__L.'/';  >);
           ">/G gescals fis);
           "f/fis;       &nbs;  = su ce d(p">$claDir ) >);
           befo eaonp"f/fiscesE$url )ye
   />       ) {
               ">/Verifiooi ie fiEss : ssNa>+ne cla + versctio+ir"t senon {
               if( is_e fi(">$claDir.$url">er&amer&am pd-r_match('/([^\.]+)\.>$cla\.([\d\.]+)\.(.+)$/',E$url,E$m ) )ye
   />   />       );    {
   />               ">/Verifioon usneee fi {
                   , ( ">$classNa ==E$m[1] )ye
   />   />           ) {
                       ">/G gepd-viousoversctio fod it {
                       $pd-viouso=hisset(p">$claF/fis[$m[1]] ) ?p">$claF/fis[$m[1]] : 0 >);
                        {
                       ">/G getasanverscti {
                       , ( "pd-vious">&l$m[2] )ye
   />   />               ) {
                           $>$claF/fis[E$m[1] ] =E$m[2] sp">/verscti {
                           $>$claF/fis= ">$claDir.$url >);
                       />}
                   /;     {
               />}
           / >);
           if( !>$cla_s exis($>$classNa) )p, incle(p">$claF/fi ">);
       />}
   />}
   l spl_autoload_registe"e claA auLoloadh) gt;