Jump to content
MakeWebGames

[OOP] How to auto load Classes


Floydian
 Share

Recommended Posts

This "How to" is for PHP >= 5.

This will not work in PHP 4.

We all know that each class definition should go in it's own file, and doing that forces us to use require(); or include(); so as to include the class definition of each class that we want to use.

This can be a tedious process of managing scripts. As PHP has evolved and improved it's OOP implementation, they have introduced a way to eliminate the need for numerous includes.

This is done by defining an __autoload(); function. Take note of the double underscore that begins the name. The PHP manual warns us to not use double underscores because any thing that has double underscores gets "magic" properties. I don't know specifically what those are, but they are documented in the manual if you want to look them up.

Here is an example of an __autoload() function.

 

<?php
// Class autoloader
function __autoload($class_name) {
   require_once (BASE_URI . 'class/' . $class_name . '.php');
}
?>

 

BASE_URI is a constant that I define in my configuration file. I contains the absolute path to my public html folder.

It would go something like this:

/home/cpanel_username/public_html/

We use require_once because IF we make two objects that are of the same class, require_once will only load the file we need one time. Using require() would prevent us from being able to use two objects with the same class in one script.

Suppose your class name was Database. You would need to put the class definition for Database into the file Database.php. That file would need to be stored in class/.

/home/cpanel_username/public_html/class/Database.php

Then when you instantiate the class:

$db = new Database();

Database is inserted here:

/home/cpanel_username/public_html/class/ >>>> Database <<<< .php

It's that simple. :)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...