Using too much include() in php

前端 未结 3 756
北荒
北荒 2021-01-18 04:30

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-

相关标签:
3条回答
  • 2021-01-18 05:19

    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);
    
    0 讨论(0)
  • 2021-01-18 05:22

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

    0 讨论(0)
  • 2021-01-18 05:23

    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');
    
    0 讨论(0)
提交回复
热议问题