Home > Article > Backend Development > Code reuse through Include and Require functions_PHP Tutorial
If you have built Web sites of various sizes, you must have a deep understanding of the importance of reusing code segments, whether it is HTML or PHP code blocks. For example, if you need to modify the footer containing copyright information once a year, and you have 1,000 Web pages (even 10), manual operation will make you miserable. With PHP, you can use different functions to help you reuse code. The exact functions you use depend on what you plan to reuse. The main function is as follows: * include() and include_once() * require() and require_once() The include() function includes the given file and checks it. For example: include(/home/me/myfile); Any code in the included file will be executed within the variable scope, which is equivalent to where the function include() appears in the parent code. You can include static files on a server or object files on another server by combining the include() and fopen() functions. The include_once() function performs the same function as the include() function, only checking whether the code in the file has been included in the current script. If the code is already included in the script, the function no longer includes the corresponding file. The require() function replaces itself with the contents of the given file. This replacement process occurs when the PHP engine compiles your code rather than during execution, unlike include(), which is evaluated first. The require() function is more used for static elements, while the include() function is mainly used for dynamic elements. Similar to include_once(), the require_once() function checks whether the given code has already been inserted into the document. If the code already exists, the given code will not be inserted into the document again. It is recommended to use the require function for information such as copyright, static text and other elements without variables. Elements that rely on other scripts to implement their own content should also use the require function, for example: