PHP Tutorials: Autoloading Classes
Undoubtedly, the release of PHP 5 has had a remarkable impact on the way that object-oriented applications are developed nowadays. This highly-improved model has provided PHP programmers with features that were only present in mature object-based languages, like Java and C++, but now, fortunately for you and me, they are generously offered by this powerful server-side scripting language.
Loading classes automatically: taking a look at the “__autoload()” PHP 5 magic function
<?php
class ClassLoader
{
//specify list of the default folders where you
//want always look for classes first
private static $default = array(
'folder/classes/',
'folder/classes/.../',
);
public static function load_class($class_name)
{
$exists = FALSE;
// iterate through the class directories
//until a match is found
foreach (self::$default as $dir)
{
if (file_exists(($include=$dir.$class_name.'.php')))
{
require_once $include;
$exists = TRUE;
break;
}
}
return $exists;
}
}
function __autoload($class_name)
{
ClassLoader::load_class($class_name);
}
Save content above into the file ClassLoader.php and make sure this file is always included at the top of your program. Enjoy!
Dima Svirid
Software architect. Ajax/Javascript, HTML5, Android, iPhone/iPad, JAVA, PHP, Cold Fusion, SQL, Air, Flash, Open source software, Frameworks
Thank you! Useful article
Thank you for reading! If you find this article useful and interesting, please click on one of our sponsor links below as a little appreciation and support.
Happy coding!
close [x]
SEARCH ARTICLES & TUTORIALS
MOST POPULAR TUTORIALS
Search Engine Optimization - Do It Yourself!
Probably most of us ever dreamed to have website at the top of the Goo[...]
jQuery Object Oriented Plugins
Many people have asked me, if jQuery is object oriented and how they c[...]
Spring-MVC Tutorial (Part 1)
Overview This document is a step-by-step guide on how to de[...]
Animated scroll to anchor method with jQuery
It's a one line but can add a really nice effect to your website. f[...]
Reload Google ads with Javascript
Reloading or refreshing your AdSense advertisements automatically isn'[...]
SPONSORED LINKS
HOTTEST TECH NEWS & RUMORS
RECENT POSTS
Dynamically display images via Java Servlet, Tomcat
This is a standard way of showing an image via Servlet. However this w[...]
Scaling Images preserving Aspect Ratio. Universal method for Java and Javascript.
While developing web application for digital publications using Java a[...]
Tomcat webapps folder in Eclipse
Eclipse provides a very convenient way to create a dynamic web applica[...]
Search Engine Optimization – Do It Yourself! (Part 3)
Content Really Matters! Yes, it is true! Your website content is real[...]
Create Canvas Image with jQuery
I usually use <img tag to create images almost for everything. Howe[...]
SPONSORED LINKS




