tags:

views:

100

answers:

2

Hi,

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 unnecessary 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.

+4  A: 

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).

Kevin Peno
+1  A: 

__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.

Anti Veeranna