This article gives you a summary of PHP include files in several cases of the scope, very simple and practical, I hope that you are familiar with the use of include can help.
In PHP, we sometimes need to include a file. For example, I spent some time in writing a framework, I intend to use native PHP as a template, and then write a display method to introduce template files can, but this is just my imagination.
When you finish writing, you find that all the variables in the template are not defined. Through a variety of research and search data, summed up the include file in several cases of the scope.
The first case: A file include B file, in the B file can call the variables in a.
A file code:
?
1 2 3 4 |
<?php $aaa = ' 123 '; Include "b.php"; |
B File Code:
?
Can output the content normally.
The second case: A file include B file, and then in a file can call the B file variables.
A file code:
?
1 2 3 4 5 |
<?php include "b.php"; Echo $fff; |
B File Code:
?
1 2 3 |
<?php $fff = ' I am f '; |
This time it is normal to output the content.
In the third case: A file in a method of a class called B file, and then in B file can call the variable in the method.
A file code:
?
1 2 3 4 5 6 7 8 9 10 11 |
<?php class test{Public function Show () {$bbb = ' abc '; include ' b.php ';}} $t = new test; $t->show (); |
The code for the B file:
?
This time it is normal to output the content.
Fourth scenario: A file introduces a B file through a defined function, the variables in a are not available in the B file, but you can use the variables in the call function (display) in a file.
A file code:
?
1 2 3 4 5 6 7 8 9 |
<?php $aaa = ' 123 '; function display ($file) {$bbb = ' asdasdas '; include $file;} Display ("b.php"); |
B File Code:
?
1 2 3 |
<?php Echo $aaa; Echo $bbb; |
$AAA prompts are undefined after running, $BBB can output normally.
So I started with a display method to introduce the template is not feasible. According to the three kinds of situations, I finally chose to write a class to import the template file. Currently thinkphp and Smarty also use classes to introduce template files. The deficiencies in the article are welcome to correct me.
The above is the entire contents of this article, I hope you can enjoy.