how to pass a variable through the require() or include() function of php?

后端 未结 9 2088
梦如初夏
梦如初夏 2021-02-06 21:34

when I use this:

require(\"diggstyle_code.php?page=$page_no\");

the warning is :failed to open stream: No error in C:\\xampp\\htdocs\\4ajax\\ga

相关标签:
9条回答
  • 2021-02-06 22:30

    require() does not make an HTTP call. All it does is open the file from disk and include the code in the position of the call. So simple local variables are enough.

    0 讨论(0)
  • 2021-02-06 22:32

    require() and include() will open the file corresponding to the path/name they receive.

    Which means that, with your code, you would have to have a file called diggstyle_code.php?page=1 on your disk. That's obviously not the case, so it fails.

    Quoting the Variable scope page of the PHP Manual:

    The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.

    In your case, you don't need to pass the variable. If you have a variable in your current script, it will also exist in the script you include, outside of functions, which have their own scope.

    In your main script, you should have:

    $page_no = 10;
    require 'diggstyle_code.php';
    

    And in diggstyle_code.php:

    echo $page_no;
    // Or work with $page_no the way you have to
    

    Remember that including/requiring a file is exactly the same as copy-pasting its content at the line it's required.

    0 讨论(0)
  • 2021-02-06 22:32

    Though this question is old there's another option that I use which is missing from this thread. You can return a function from the required file which accepts the arguments you want to pass along:

    return function(array $something) {
        print_r($something);
    }
    

    And call it with the arguments when you require it:

    require('file.php')(['some', 'data']);
    
    // or:
    
    $context = require('file.php');
    $context(['some', 'data']);
    
    0 讨论(0)
提交回复
热议问题