如何将代码片段从一个 PHP 文件包含到另一个 PHP 文件


how to include code snippet from one php file to another one?

我刚刚了解了PHP中的include()函数,它可以将整个文档包含在另一个文档中。 我想知道如何做同样的事情,如果我想不包括整个文档,而只是一段代码,从一个文档到另一个文档。

您可以使用 2 种方法:

  • 你可以按照@blckbird的想法,把你的代码放在一个新文件中,然后把它包含在内。
  • 你可以用你的截图代码创建一个包含方法foo()的文件。 包含该文件并调用该foo()。

例如:

帮助程序.php - 包含您的截图/可重用代码

<?php 
function startPage($title){
    print '
    <!DOCTYPE html>
    <html>
        <head>
            <title>'.$title.'</title>
        </head>
        <body>';
}
function endPage(){
    print '
        </body>
    </html>';'
}
?>

现在,您的主文件包含帮助程序.php并调用所需的方法。主.php

<?php 
include("helper.php");
startPage("My Title");
// do your stuff/coding here
endPage();
?>

希望它有所帮助。