dpvhv66448 2015-07-21 16:21
浏览 29
已采纳

PHP:如何在一些但不是所有页面上包含代码片段

I am new to PHP and programming in general and hope someone can help me with this.

I am working on building a website where the code for each page is saved in a separate file.

Now I have a couple of code snippets that I want to use on different pages but not on all of them. My current approach is that I paste them on every file that uses them which duplicates code and therefore supposedly is not good practice.

On the other hand when I use snippets on all pages I have removed them from the single files and store them as separate includes files using PHP's include or require in order to include them on a page, e.g. for the header, the footer and the menu etc. - example:

require_once("includes/header.php");

This works well and I was wondering if there is a similar way I can include the other code snippets as well BUT without having to save each of them as a separate file.

Is there a way for example that I could use functions for this or is there some other common practice ?

Example (just to show what I mean):

<?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 />";
?>

The pieces to insert could be anything but usually they are some small PHP / HTML snippets, like a set of buttons or a div or a dropdown etc.

  • 写回答

2条回答 默认 最新

  • dswmmvrg40957 2015-07-21 17:14
    关注

    Make the code snippets inside a function so you can call it on any other page by including the same page everytime. Let's say we have an index.php page, and we have a test.php that have this code (that we want to include on the index page):

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

    Now, in the index.php page, we put:

    <?php
    include('test.php');
    ?>
    <h1><?php hello(); ?></h1>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)