Sunday, 13 January 2013

Where and How to use autoload function in PHP?

Many a times when we use OOP in PHP we define class files and include it in our code. But in PHP we can include class file on the go using autoload function.

function __autoload($class_name)
$file_path = "PATH_TO_CLASS_FILE";
if (file_exists($file_path))

The above code can be written any where in our code, at run time when we wish to create a object of any class, it will include the class file on the go and function would be accessed and required operation can be performed.

To explain the above with example, consider you created a class file in suppose “classes” folder and named it as “login.class.php” and while executing the code you create the object of the login class as

$obj = new login;

While executing the above code, it will first include the login class file and object would be created.

The advantages of this is that we can use n no of class files within a page without checking or including all class files manually

No comments:

Post a Comment