Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP __autoload performance

Tags:

php

autoload

I have a script that uses autoload to load classes that aren't found. I don't deliberately include the 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_exists on each recursion of the script.

like image 471
CoCoMo Avatar asked Jul 26 '10 00:07

CoCoMo


People also ask

What is autoload PHP used for?

By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error. Any class-like construct may be autoloaded the same way. That includes classes, interfaces, traits, and enumerations. Prior to PHP 8.0.

What is the relation of Namespacing and autoloading PHP files?

Basically it says: "inside this directory, all namespaces are represented by sub directories and classes are <ClassName>. php files." Autoloading is PHP's way to automatically find classes and their corresponding files without having to require all of them manually.

What is spl_autoload_register?

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared.

What is magic functions and auto loading in PHP?

In PHP __autoload() is a magic method, means it gets called automatically when you try create an object of the class and if the PHP engine doesn't find the class in the script it'll try to call __autoload() magic method. You can implement it as given below example: function __autoload($ClassName) { include($ClassName.


1 Answers

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.

like image 147
Artefacto Avatar answered Oct 05 '22 07:10

Artefacto