TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Tips & Tricks (http://www.talkphp.com/tips-tricks/)
-   -   Tip: Autoloading class files (http://www.talkphp.com/tips-tricks/1014-tip-autoloading-class-files.html)

Karl 09-06-2007 12:07 AM

Tip: Autoloading class files
 
You can autoload class files using the __autoload() function. Simply define the function with a single argument (this will be the name of the class) .

Code:

function __autoload($szClassName)
{
                $szFilePath = "lib/$szClassName.php";
               
                if (file_exists($szFilePath))
                {
                        include_once($szFilePath);
                }
}

Now if you try to instantiate a class that is unknown, PHP will first try to load the class file via the code we setup in the __autoload funciton before throwing a fatal error.

Salathe 09-06-2007 01:37 PM

Your code snippet will not work as-is. You assign $szFileName but then use $szFilePath in the file_exists and include_once calls.

Karl 09-06-2007 01:43 PM

ah yes lol, sorry. Wrote it from the top of my head, guess I should have checked it first. All fixed up now :)


All times are GMT. The time now is 07:39 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0