Home » Php » Using too much include() in php

Using too much include() in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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');

Answer:

Instead of using include you may want to look into autoloading.

Answer:

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);