简体   繁体   中英

Using require and include from PHP class to load outside the class

I've been attempting to create a PHP loader class that'll take care of all of my directory issues. I've mostly gotten it to work, but it breaks when including global functions.

Here's what I'm using:

<?php
class Loader {
    public function __construct() { ... }
    private function check_if_file_exists($file) { ... }
    public function load($file) {
        $this->check_if_file_exists($file); //Throws fatal Exception if not a file
        //The "important" stuff: works with global vars, not with global functions:
        extract($GLOBALS, EXTR_REFS);
        ob_start();
        require_once "{$this->path}/$file";
        return ob_get_clean();
    }
}

This lets me do the following:

<?php
$loader = new Loader();
$loader->load('file.php'); //Class takes care of path stuff--don't worry about it
//This works:
print $variable_in_file_dot_php;

//This does NOT work:
function_in_file_dot_php();

How can I make it so that function_in_file_dot_php(); works?

最好使用php中已经可用的AutoLoader类。请参考以下URL http://php.net/manual/zh/language.oop5.autoload.php

i'm going to try to answer your question as a technical curiousity , but i strongly advise you not to do this.

Referring to the include/require documentation I see that variables defined inside included files will inherit the variable scope of the line that called require. In your case this will be the variable scope of Loader::load() method inside some instance of Loader class

Therefore $variable_in_file will not be available globally. unless you

  1. define the $var before calling the include statement, thus giving it global scope.
  2. declare it global inside your calling method (Loader::load())

You acomplish #2 with extract($GLOBALS...) however in order to do #1, you must have a priori knowledge of what is being included before you include it... invalidating your attempt at generalization with the Loader class.

function_in_file() however should be available in the global scope, I'd like to see your file.php and error message. Here's mine.

$cat foo.php

    public function load($file) {
        extract($GLOBALS,EXTR_REFS);
        require_once $file;
    }
}

$variable = 1;

$loader = new Loader();
$loader->load('file.php');

echo  "\n" . $variable;

echo "\n" .  method();

$cat file.php

<?php
function method() {
    echo "hi i am a method";
}

outputs

$php foo.php 
hello i am a variablehi i am a method

but seriously, don't do this. You seem to be trying to use includes() as a vector of code reuse, when it is mostly envisioned as a method for code separation. You are messing with phps' natural scoping in a hard to debug and unpredictable way. This is an anti-pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM