【问题标题】:PHP: How to include code snippets on some but not all pagesPHP:如何在某些但不是所有页面上包含代码片段
【发布时间】:2015-10-11 05:30:39
【问题描述】:

我是 PHP 和一般编程的新手,希望有人可以帮助我。

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

现在我有几个代码 sn-ps 我想在不同的页面上使用,但不是在所有页面上使用。 我目前的方法是我将它们粘贴到每个使用它们的文件上,这些文件复制了代码,因此被认为不是一个好习惯。

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

require_once("includes/header.php");

这很好用,我想知道是否有类似的方法可以也包含其他代码 sn-ps,但不必将它们中的每一个保存为单独的文件

有没有办法,例如,我可以为此使用函数,还是有其他一些常见的做法?

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

<?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 sn-ps,例如一组按钮或一个 div 或一个下拉列表等。

【问题讨论】:

    标签: php html function include require


    【解决方案1】:

    将代码 sn-ps 放在一个函数中,这样您就可以通过每次包含相同的页面在任何其他页面上调用它。 假设我们有一个 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>
    

    【讨论】:

    • 太棒了——这正是我的想法,而且效果很好。非常感谢 ! :)
    • 很高兴这有帮助:)
    【解决方案2】:

    使用单个 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';
    

    【讨论】:

    • 谢谢你 - 我喜欢这种方法!但是,我不确定我是否可以那样使用它。例如,如果一个页面需要 sn-p 1、3、7 和另一个 3、7、10 并且页面中的不同位置需要 sn-ps,我会在这里做什么?我在想我可以调用一个函数等,而不仅仅是在需要的地方回显相应的 sn-p。
    • 您可以使用另一种方法,将所有文件放在一个文件夹中并检查它们是否存在并包含为 $_GET 而不是 switch/case
    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 2018-04-19
    • 2021-12-03
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多