On the scope of include file variables in PHP
This article summarizes the PHP include files in the scope of several cases, very simple and practical, I hope you are familiar with the use of include can be helpful.
In PHP we sometimes need to include a file. For example, I used to write a framework, I intend to use the original PHP as a template, and then write a display method to introduce template file, but this is just my fantasy.
After writing, it is found that all variables in the template are not defined. The scope of the include file is summarized in several cases through various research and search data.
The first case: A file include B file, in B file can call a variable.
A file code:
?
1 2 3 4 |
$AAA = ' 123 '; Include "b.php"; |
B File Code:
?
The content can be output normally.
The second case: A file include B file, and then in a file you can call the B file variable.
A file code:
?
1 2 3 4 5 |
Include "b.php"; Echo $fff; |
B File Code:
?
This time, the content can be output normally.
In the third case, a method in a class of a file invokes the B file, and then the variable in the method can be called in the B file.
A file code:
?
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 (); |
B file's code:
?
This time, the content can be output normally.
The fourth case: A file introduces a B file through a defined function, the variable in a is not available in the B file, but you can use the variable in the call function (display) in the a file.
A file code:
?
1 2 3 4 5 6 7 8 9 |
$AAA = ' 123 '; function display ($file) { $bbb = ' Asdasdas '; Include $file; } Display ("b.php"); |
B File Code:
?
After running the $aaa prompt is undefined, $bbb can output normally.
So it's not feasible for me to start by using a display method to introduce a template. Based on three scenarios, I finally chose to write a class to import the template file. At present, thinkphp and Smarty also use classes to introduce template files. The shortcomings of the text welcome correction.
The above mentioned is the whole content of this article, I hope you can like.
http://www.bkjia.com/PHPjc/1018370.html www.bkjia.com true http://www.bkjia.com/PHPjc/1018370.html techarticle A brief talk on the scope of include file variables in PHP This article summarizes the PHP include files in the scope of the various cases, very simple and practical, I hope you are familiar with the use of include can ...