Archive

Posts Tagged ‘oop’

Autoloading objects in PHP

June 11th, 2008 No comments

 When doing OOP in PHP it can be a pain to include all the different class files. The code becomes really ugly with lots of require_once() function calls and you risk to include classes that are never used.

This is were object autoloading comes in handy. In PHP 5 it is now possible to define a functions called __autoload() which takes the name of the class as parameter. The function will be called when trying to use a class or an interface that has not been defined yet. The function could look like this

function __autoload($class_name){
require_once('/classes/'.$class_name.'.php');
}
$obj = new MyClass(); //will load MyClass from /classes/myclass.php
MyClass::getSomething() //will load MyClass from /classes/myclass.php