php – include, require within functions methods


Can using include (or require ) inside a function or method cause a conflict or problem with older versions of PHP (like 5.3)?

I noticed that most frameworks that work with MVC use require inside a method, for example CodeIgniter3's ./CodeIgniter/system/core/Loader.php file:

public function model($model, $name = '', $db_conn = FALSE)

    foreach ($this->_ci_model_paths as $mod_path)
        if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))


        $this->_ci_models[] = $name;
        $CI->$name = new $model();
        return $this;

    show_error('Unable to locate the model you have specified: '.$model);

I believe that all PHP FrameWorks based on routes (and mvc) work like this, so maybe this is something that doesn't cause problems in recent versions of PHP, but I would like to know regarding version 5.3 if there is any problem (I won't use the version 5.3 is just curiosity).

My concern is because require usually includes a class (coming from Model or Controller usually) at runtime and in API (PHP) behavior.


There is no problem in doing includes inside functions, what changes is just the scope. If you include inside the function, the include scope is only inside that function, that is, it would be as if that included code were typed inside the function.

This answer can be found on the PHP website in the include statement documentation: .

If the include takes place inside a function all the code contained in the included file will behave as if it had been defined inside the function. So it will follow the scope of the function's variables. An exception to this rule is magic constants that are interpreted before the inclusion takes place.

// Object.php
return new Object();

// Classe.php
class Classe {
    public static function createObject(){
         include_once 'Object.php';

// file.php
$object = Classe::createObject();
var_dump($object instanceof Object); //true
Scroll to Top