I have a habit of using include() a lot in my php scripts. I would like to know is it a good approach. I just use include a lot because it makes code look-better for future-proof programming.
3 Answers
make use of php autoloading function
example:
function __autoload($class_name) {
include $class_name . '.php';
}
whenever you instantiate a new class. PHP automagically calls the __autoload function with one argument i.e the class name. consider the below example
$user = new User():
when you instantiate the user object here the autoload function is called, it tries include the file from the same directory. (with reference to above autoload function). now you could implement your own logic to autoload classes. no matter in which directory it resides. for more information check out this link http://in.php.net/autoload.
Update: @RepWhoringPeeHaa, you said it correct buddy. there are more benefits in using spl_autoload then simple autoloading function. the major benefit i see is that more than one function can be used or registered.
for example
function autoload_component($class_name)
{
$file = 'component/' . $class_name . '.php';
if (file_exists($file)) {
include_once($file);
}
}
function autoload_sample($class_name)
{
$file = 'sample/' . $class_name . '.php';
if (file_exists($file)) {
include_once($file);
}
}
spl_autoload_register('autoload_component');
spl_autoload_register('autoload_sample');

- 9,165
- 5
- 37
- 58

- 25,288
- 35
- 131
- 207
-
@yusufiqbalpk , if you want to learn more. i suggest you start by learning the concepts of OOPS in PHP. here is the link to get you started http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/ – Ibrahim Azhar Armar Apr 24 '12 at 15:46
-
1All answers were good but I choose you for your tutorial link. Best guy. – yusufiqbalpk Apr 24 '12 at 15:57
-
1@yusufiqbalpk you might want to consider the 'new' `spl_autoload` instead of the above. – PeeHaa Apr 24 '12 at 16:07
If you're developing object-orientated and have a file for each class, consider implementing an autoloader function that automatically calls include
when a class is used but not yet loaded:
$callback = function($className) {
// Generate the class file name using the directory of this initial file
$fileName = dirname(__FILE__) . '/' . $className . '.php';
if (file_exists($fileName)) {
require_once($fileName);
return;
}
};
spl_autoload_register($callback);

- 9,165
- 5
- 37
- 58
-
I have never used it. For that I have to first learn. So where can I learn it ? A link maybe helpful. Thanks in Advance – yusufiqbalpk Apr 24 '12 at 15:42