tags:

views:

130

answers:

2

I have a script that uses autoload to load classes that arn't found. I don't deliberately include file though i can but i would like the autoload function to include the required files , because the script can be recursive that is if the class is already loaded i don't want to check the corresponding file is loaded and if class_exist on each recursion of the script. Please give me suggestion.

+3  A: 

If you want to avoid __autoload, you can use require_once instead of include.

The performance hit of using __autoload may be considerable, especially because some opcode caches do not support it properly. However, given it's very handy, I'd say use it unless your opcode cache does not cache autoload includes.

Artefacto
Don't forget there is also `include_once()`.
alex
@alex I prefer to steer people way from `include` unless absolutely necessary (and it very rarely is). Being a construct that fails more or less silently when the file doesn't exist, it's stolen me a few hours of life.
Artefacto
@Artefacto Agreed, just thought I'd mention it. Also, opcode cache stuff is useful so +1
alex
@Artefacto: which opcode caches cannot handle `__autoload`? I haven't encountered a problem with apc int that respect yet...
Wrikken
@Wrikken I wasn't more specific because I didn't remember :p I read it somewhere in IRC referring to APC; by "not handling" I mean "the auto-loaded scripts would not be cached".
Artefacto
I believe that, like the old performance "rule" about require/include_once, the problem with bytecode caches and autoloading is a PHP4-ism.
Charles
+2  A: 

If you have your autoloader set up to load your classes and aren't using require (et al.) the autoloader will only be called if a class is referenced that doesn't exist. So there is never a need to check class_exists in the autoloader (it won't be called if the class exists).

With regard to performance. If you are using large libraries, autoload can actually be faster as it only loads the files/classes that are required. Either way the speed hit is pretty negligible in my experience (always use an opcode cache, as others have mentioned).

Brenton Alker
I was not talking about using class_exist inside autoload.. I meant if i don't use autoload function i had to use class_exist before trying to access the class, I mean't i would do the autoload stuff manually which is if class doesn't exist include some file and than try again and as the script will be recursive i would be doing it checking the same thing even for the classes that are already loaded.