PHP: 如何在部分而非所有页面上包含代码片段

PHP: How to include code snippets on some but not all pages

我不熟悉 PHP 和一般的编程,希望有人能帮助我。

我正在构建一个网站,其中每个页面的代码都保存在一个单独的文件中。

现在 我有几个代码片段想在不同的页面上使用,但不是在所有页面上使用。 我目前的方法是将它们粘贴到每个使用它们的文件上,这会重复代码,因此这不是好的做法。

另一方面,当我在所有页面上使用片段时,我已将它们从单个文件中删除并使用 PHP 的 includerequire 将它们存储为单独的包含文件为了将它们包含在页面上,例如用于页眉、页脚和菜单等 - 例如:

require_once("includes/header.php");

这很好用,我想知道是否有类似的方法可以包括其他代码片段,但不必将它们每个都保存为单独的文件

有没有一种方法可以为此使用函数,或者是否有其他一些常见做法?

示例(只是为了说明我的意思):

<?php
    // example of what I would like to include on different pages
    echo "<button type="button" class="class1" id="btn1">Button 1</button><br />
        <button type="button" class="class2" id="btn1">Button 2</button><br />
        <button type="button" class="class3" id="btn1">Button 3</button><br />";
?>

要插入的内容可以是任何内容,但通常是一些小的 PHP / HTML 片段,例如一组按钮或 div 或下拉菜单等。

使用一个 index.php 文件来处理其余的

index.php

<?php
require_once 'header.php';
if(isset($_GET['page']){
    switch($_GET['page']){
        case "123":
         require_once 'snippet1.php';
        break;
        case "1234":
         require_once 'snippet2.php';
        break;
        default:
         require_once 'notfound.php';
    }
}
require_once 'footer.php';

将代码片段放在一个函数中,这样您就可以通过每次都包含同一页面在任何其他页面上调用它。 假设我们有一个 index.php 页面,并且我们有一个 test.php 包含此代码(我们希望包含在索引页面中):

    <?php
function hello(){
echo 'Hello World!';
}
hello(); //to print "hello world!" in this particular page
?>

现在,在 index.php 页面中,我们输入:

<?php
include('test.php');
?>
<h1><?php hello(); ?></h1>