Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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

when I use this:

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

the warning is :failed to open stream: No error in C:xampphtdocs4ajaxgallery_core.php on line 198

and the error is:

Failed opening required 'diggstyle_code.php?page=1' (include_path='.;C:xamppphpPEAR') in C:xampphtdocs4ajaxgallery_core.php on line 198

value of the variable $page_no is collected beforehand.

But if I omit the '?page=$page_no part' from the argument of the require function, then no error or warning is shown.

I need to pass the variable when I use the require() function.

question from:https://stackoverflow.com/questions/5128137/how-to-pass-a-variable-through-the-require-or-include-function-of-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...