__autoload

(PHP 5, PHP 7)

__autoloadПопытка загрузить неопределённый класс

Внимание

Эта функция объявлена УСТАРЕВШЕЙ начиная с PHP 7.2.0 и была УДАЛЕНА в версии PHP 8.0.0. Использовать эту функцию крайне не рекомендуется.

Описание

__autoload(string $class): void

Вы можете определить эту функцию для автозагрузки классов.

Список параметров

class

Имя загружаемого класса

Возвращаемые значения

Функция не возвращает значения после выполнения.

Смотрите также

  • spl_autoload_register() - Регистрирует заданную функцию в качестве реализации метода __autoload()

add a note add a note

User Contributed Notes 7 notes

up
46
ohcc at 163 dot com
10 years ago
It is highly recommended not to use the __autoload() function any more. Now the spl_autoload_register() function is what you should consider.
<?php
   
if(!function_exists('classAutoLoader')){
        function
classAutoLoader($class){
           
$class=strtolower($class);
           
$classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';
            if(
is_file($classFile)&&!class_exists($class)) include $classFile;
        }
    }
   
spl_autoload_register('classAutoLoader');
?>
up
45
qeremy
12 years ago
Even I have never been using this function, just a simple example in order to explain it;

./myClass.php
<?php
class myClass {
    public function
__construct() {
        echo
"myClass init'ed successfuly!!!";
    }
}
?>

./index.php
<?php
// we've writen this code where we need
function __autoload($classname) {
   
$filename = "./". $classname .".php";
    include_once(
$filename);
}

// we've called a class ***
$obj = new myClass();
?>

*** At this line, our "./myClass.php" will be included! This is the magic that we're wondering... And you get this result "myClass init'ed successfuly!!!".

So, if you call a class that named as myClass then a file will be included myClass.php if it exists (if not you get an include error normally). If you call Foo, Foo.php will be included, and so on...

And you don't need some code like this anymore;

<?php
include_once("./myClass.php");
include_once(
"./myFoo.php");
include_once(
"./myBar.php");

$obj = new myClass();
$foo = new myFoo();
$bar = new myBar();
?>

Your class files will be included "automatically" when you call (init) them without these functions: "include, include_once, require, require_once".
up
2
sham dot hrm at gmail dot com
3 years ago
We you create an object of the class and If the PHP engine doesn't find the class file included in the script then __autoload() magic method will automatically trigger.

You can implement it as given below example:

<?PHP
function __autoload($ClassName)
{
    include(
$ClassName.".php");
}
$obj = new Base;
?>
up
-1
eragroove at gmail dot com
10 years ago
If you can keep file name and class name as same, it will be good programming practice. It helps to __autoload function to load file without checking any condition.
 
function __autoload($class){
  require_once( $class.".php");
}
up
-5
ohcc at 163 dot com
6 years ago
In PHP 7.2, this code will trigger a "
Deprecated: __autoload() is deprecated, use spl_autoload_register() instead in path\to\file.php on line *" error although the spl_autoload_register function really really exists.
<?php
   
if(!function_exists('spl_autoload_register')){
        function
__autoload($class){
           
// blah blah blah
       
}
    }
?>
up
-9
Jose G
9 years ago
You should use include() or require() inside __autoload()
instead of include_once() or require_once().

If you reach __autoload(), then you know the file with the class definition has not been loaded yet.

include() and require() are more efficient than include_once() and require_once().
up
-18
Ben
9 years ago
Guys, this document ( i mean __autoload() ) not mentioned one special situation: if you both use __autoload() and spl_autoload_register(), the __autoload() function will never to be called. Although spl_autoload_register() documentation explained why, i decide to wrote this in case some one get confused and waste all day to figure out why.

Here is some code to verify above:

<?php
function __autoload($class) {
}

function
my_loader() {
}

function
your_loader() {
}

var_dump ( spl_autoload_functions () );
echo
'<br/>';

spl_autoload_register ( 'my_loader' );
spl_autoload_register ( 'your_loader' );

var_dump ( spl_autoload_functions () );
To Top