开发者

How to skip using __autoload?

开发者 https://www.devze.com 2022-12-09 04:16 出处:网络
I have a php file which has multiple classes in it. I noticed that __autoload is being called when I instantiate any of the classes, even after the \'package\' file has been autoloaded. This is worryi

I have a php file which has multiple classes in it. I noticed that __autoload is being called when I instantiate any of the classes, even after the 'package' file has been autoloaded. This is worrying me, because surely if the initial 'package' .php file has been loaded, it is un开发者_如何学运维necessary overhead for __autoload when the classes have already been loaded.

I probably made a hash of explaining that, so here is an example:

<?php
class Class1{};
class Class2{};
?>

Then in another file:

<?php
new Class1;
new Class2;
?>

__autoload will be used for both Class1 AND Class2's instantiation... even though they are housed in the same file.

Is there a way to get around this?

Sorry if my explanation isn't very good, I'd really appreciate any help or tips.


PHP's autoload should only be called if a class doesn't exist. In other words, for the most basic example, it uses the same logic as:

if( !class_exists("Class1") )
    require "path\Class1.php"; 

If you are finding otherwise, I would check to be sure you are doing everything correctly and report a bug.

From PHP.net/autoload (important documentation highlighted):

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Bug in formatting, but the emphasis was on "which hasn't been defined yet". "Defined" occurs when a class is compiled (in most cases when a file containing said class is included).


__autoload is definitely NOT called the second time, when Class2 got defined as result of the first call.

First classes.php

<?php
class Class1 {};
class Class2 {};

Now test.php

<?php
function __autoload ($class)
{
    print "Autoloading $class\n";
    require 'classes.php';

}

$a = new Class1;
$b = new Class2;

print get_class($b);

When you run test.php, the result is:

Autoloading Class1
Class2

If you are getting different result, then there is something that you are not telling us.

0

精彩评论

暂无评论...
验证码 换一张
取 消