PHP Include


In our actual production work, when building a larger system, there are always some content that needs to be reused, such as some commonly used functions, or some common html elements such as menus, footers and so on. We can put the contents of these public written in some documents, and then according to the specific circumstances, where needed to include, so you can save a lot of development time, the code file concise and concise, in order to facilitate better maintenance.


The include() and require() statements are all available for inclusion of such files.

The following example demonstrates the use of the file.

Create a file.php file:

$word = "Hello!";

And then include it in another file, such as test.php(both files in the same directory):

echo "contains the content: ". $word. "<br />";

Include("file.php ");
echo "contains the contents of: ". $word;

Run test.php output is as follows:

Contains:
Contains content: Hello!

As you can see from the above example, an include file can be understood as a part of the include() statement that will be used to replace the included file. After the file is included, the contents of the included file become part of the current file, and the contained content is also taken into account.


The difference between include() and require()

the require() statement can also be used to include a file, which is equivalent to include(). But they also have some nuances, depending on the actual situation using include() or require().


The difference between the two is as follows:

  1. When the include file does not exist(including the occurrence of an error), if the use of require(), the program immediately stop the implementation of the use of include(), the system in addition to error, the following program will continue. In most cases require the use of require() function, in order to avoid the wrong reference to continue the proceedings after the implementation of
  2. Regardless of whether the require() statement is executed, the program execution include file is added, and include() is only included if the file is executed. So if it is conditional to judge the case, use include() is clearly more appropriate
  3. When using require() multiple references, only one reference to the referenced file is executed, and include() is read and evaluated each time the file is referenced.



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook