Classes/Object 函数
在线手册:中文 英文
PHP手册

__autoload

(No version information available, might only be in SVN)

__autoloadAttempt to load undefined class

说明

void __autoload ( string $class )

You can define this function to enable classes autoloading.

参数

class

Name of the class to load

返回值

没有返回值。

参见


Classes/Object 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: Attempt to load undefined class

用户评论:

carloagonzales at gmail dot com (04-Apr-2012 09:42)

__autoload magic function can also be used inside a class and have the class handle the inclusion of class files.

/********
index.php
********/
<?php

class foobar {
    public function
executeMe(){
        function
__autoload($classname){
            include
$classname . '.php';
        }
    }
}

$foo = new foobar();

$foo->executeMe();
some::foobar2(); //will output "hello! I'm static!"

$bar = new some();
$bar->foobar(); //will output "hello! I'm public!"
?>

/********
some.php
********/

<?php
class some {

    public function
foobar (){
        echo
"hello! I'm public!";
    }

    static function
foobar2 (){
        echo
"hello! I'm static!";
    }
}
?>

juan dot carlos dot montilla at gmail dot com (14-Mar-2012 08:45)

If your __autoload implementation is not working...

Check if spl_autoload_register() is being called before __autoload.

PHP 5.3 and PHP 5.4 will completely ignore __autoload.

It happened to me after adding Smarty to my web application.

NOTE: This is an exact duplicate from this comment: http://www.php.net/manual/en/language.oop5.autoload.php#104282 .

Sadly i didn't see it until i discovered this issue myself.

Cheers.

qeremy (08-Mar-2012 11:01)

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 Foo();
$bar = new Bar();
?>

Your class files will be included "automatically" when you call (init) them without these functions: "include, include_once, require, require_once".