PHP Autoloading Class

PHP Programming Start to End

PHP Programming Start to End

Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary with the help of PHP autoloading class. The spl_autoload_register() function registers any number of autloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.


There are three ways to use autoloading classes and they are listed below.

Method 1# Using spl_autoload_register() is the preferred method since is a more flexible alternative (enabling for any number of autoloaders to be specified in the application, such as in third party libraries

Since PHP 5.3.0, anonymous classes can be used as an autoloader

This is the most widely used but not flexible enough, priort to PHP 5.3.0, all exceptions  thrown inside the autoloader was could not be caught in the catch block and would result in a fatal error.


Examples

Load MyClass1.php and MyClass2.php automatically

Use a try/catch block to trap errors

 

coderinthebox

The TechnoJunkie of the group who studied engineering but got stuck with software development. Remember kids, 90% of your problems can be solved by marketing. Solving the other 10% just requires good procrastination skills.

You may also like...

Leave a Reply

%d bloggers like this: