Home > Article > Backend Development > A brief discussion on the variable scope of include files in PHP_PHP Tutorial
This article summarizes the scope of several situations when including files in PHP. It is very simple and practical. I hope it will be helpful to you. It can be helpful for everyone to be familiar with the use of include.
Sometimes we need to include a file in php. For example, when I was writing a framework some time ago, I planned to use native PHP as the template, and then write a display method to introduce the template file, but this was just my imagination.
After finishing writing, I found that all variables in the template were undefined. Through various research and searching for information, I summarized the scope in several situations when including files.
The first situation: File A includes file B, and variables in A can be called in file B.
A file code:
ใ?
2 3
4 |
$aaa = '123';
include "B.php";
|
1 2 3 |
$fff = 'i am f'; |
ใ?
1 2 3 |
|
<๐>1<๐> <๐>2<๐> <๐>3<๐> <๐>4<๐> <๐>5<๐> | <๐> <๐> <๐> <๐> <๐>include "B.php";<๐> <๐> <๐> <๐>echo $fff;<๐> <๐> |
<๐>1<๐> <๐>2<๐> <๐>3<๐> | <๐> <๐> <๐> <๐> <๐>$fff = 'i am f';<๐> <๐> |
<๐>1<๐> <๐>2<๐> <๐>3<๐> <๐>4<๐> <๐>5<๐> <๐>6<๐> <๐>7<๐> <๐>8<๐> <๐>9<๐> <๐>10<๐> <๐>11<๐> | <๐> <๐> <๐> <๐> <๐>class test{<๐> <๐>public function show(){<๐> <๐>$bbb = 'abc';<๐> <๐>include "B.php";<๐> <๐>}<๐> <๐>}<๐> <๐> <๐> <๐>$t = new test;<๐> <๐>$t->show(); |
1 2 3 |
At this time, the content can be output normally.
The fourth situation: File A imports file B through a defined function. Variables in A cannot be used in file B, but variables in the calling function (display) in file A can be used.
A file code:
ใ?
2 3
4 5 6 78 |
$aaa = '123';
function display($file){
$bbb= 'asdasdas';
include $file;
}
display("B.php");
|
1 2 3 |