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.