This article summarizes the scopes of the include file in php in several cases. It is very simple and practical, and I hope it will be helpful for you to be familiar with the use of include. In php, we sometimes need to include a file. For example, when I was writing a framework some time ago, I planned to use the native php as the template and then write a display method to introduce the template file. But this is just my obscenity.
After writing the Code, all the variables in the template are prompted to be undefined. The scope of the include file is summarized through various research and searching materials.
First case:File A Includes file B. In File B, you can call the variable in file.
File A code:
<?php $aaa = '123'; include "B.php";
File B code:
<?phpecho $aaa;
The output content is normal.
Case 2:File A Includes file B, and then the variable of file B can be called in file.
File A code:
<?phpinclude "B.php";echo $fff;
File B code:
<?php$fff = 'i am f';
At this time, the content can be output normally.
Case 3:A class in file A calls file B in A method, and then the variable in this method can be called in file B.
File A code:
<?phpclass test{ public function show(){ $bbb = 'abc'; include "B.php"; }}$t = new test;$t->show();
File B code:
<?phpecho $bbb;
At this time, the content can be output normally.
Case 4:File A introduces file B through A defined function. In File B, variables in file A cannot be used, but variables in function (display) can be called in file.
File A code:
<?php$aaa = '123';function display($file){ $bbb= 'asdasdas'; include $file;}display("B.php");
File B code:
<?phpecho $aaa;echo $bbb;
After running $ aaa, the prompt is undefined. $ bbb can be output normally.
Therefore, it is not feasible for me to use a display method to introduce the template. Based on the three situations, I finally chose to write a class to import the template file. Currently, both ThinkPHP and Smarty use classes to introduce template files. If you have any shortcomings, please confirm them.
The above is all the content of this article. I hope you will like it.