downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

call_user_method_array> <类/对象 函数
[edit] Last updated: Thu, 20 Jun 2013

view this page in

__autoload

(PHP 5)

__autoload尝试加载未定义的类

说明

void __autoload ( string $class )

你可以通过定义这个函数来启用类的自动加载

参数

class

待加载的类名。

返回值

没有返回值。

参见



call_user_method_array> <类/对象 函数
[edit] Last updated: Thu, 20 Jun 2013
 
add a note add a note User Contributed Notes __autoload - [3 notes]
up
13
qeremy
1 year 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 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".
up
1
keyboardSmasher
2 months ago
qeremy, your code is incorrect.

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

$obj = new myClass();
$foo = new Foo();
$bar = new Bar();
?>

<?php
$foo
= new Foo();
$bar = new Bar();
?>

should be:

<?php
$foo
= new myFoo();
$bar = new myBar();
?>
up
0
wojciech.fornal@gmail,com
12 days ago
keyboardSmasher

You may or may not be right as the file name doesn't necessarily have to reflect a class name it contains (but it's usually considered a good practice). It isn't always a straightforward mapping (look at some PHP frameworks and autoload implementations).

File myBar.php may contain the class:

class Bar {
}

or it even contain the class:

class Foo {
}

Best regards

 
show source | credits | sitemap | contact | advertising | mirror sites