Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to use autoloading in PHP?

Tags:

oop

php

autoload

From php.net:

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.

Now I am wanting to know, is it bad practice to solely use __autoload to load the appropriate classes on a dynamic site?

The way my site is setup is to include files into the index.php file, for example http://www.site.com/index.php?p=PAGE-I-WANT-TO-LOAD

So if I am on the forums section or the blogs section of my site, I want only appropriate classes and functions to be loaded, so I use autoload but I never include a file manually, should I be using __autoload as a last resort or is what I am doing fine even on a high traffic system?

like image 747
JasonDavis Avatar asked Sep 10 '09 22:09

JasonDavis


2 Answers

Bad? No. __autoload() is one of my favorite additions to PHP 5. It removes the responsibility (and annoyance) of manually having to include/require the class files necessary to your application. That being said, it's up to you as the developer to ensure that only the 'appropriate classes' are loaded. This is easily done with a structured naming scheme and directory structure. There are plenty examples online of how to properly use __autoload(), do a Google search and you'll find plenty of information.

like image 162
Steven Mercatante Avatar answered Sep 29 '22 17:09

Steven Mercatante


Autoload is a good way to load only what classes is needed.

In PHP 5 >= 5.1.2, most of the problems with the old __autoload() dissapeared, thanks to spl_autoload_register().

like image 31
gnud Avatar answered Sep 29 '22 17:09

gnud