In PHP, I have been using functions to render reusable HTML components instead of using `include` or `require`. This approach allows me to pass parameters and dynamically modify the generated output. Here’s a simple example:
function footer($title) {
?>
<footer><?= $title ?></footer>
<?php
}
<html>
<body>
<?php footer("My Website"); ?>
</body>
</html>
I find this method useful because it allows me to create "components" with parameters, making them more flexible than static `include` files. However, I rarely see this approach being discussed in PHP best practices. Most sources recommend using `include` or `require`, like this:
// footer.php
<footer><?php echo $title ?? 'Default Title'; ?></footer>
// main file
<html>
<body>
<?php
$title = "My Website";
include 'footer.php';
?>
</body>
</html>
This method relies on global variables or manually passing values, which I find less intuitive than function parameters.
Another alternative is using `ob_start()` to capture output and return it as a string:
function footer($title) {
ob_start();
?>
<footer><?= $title ?></footer>
<?php
return ob_get_clean();
}
<html>
<body>
<?php echo footer("My Website"); ?>
<!-- OR -->
<?= footer("My Website") ?>
</body>
</html>
This method provides more flexibility in how the output is handled.
Another variation is directly returning a string inside the function:
function footer($title) {
return "<footer>$title</footer>";
}
<html>
<body>
<?php echo footer("My Website"); ?>
<!-- OR -->
<?= footer("My Website") ?>
</body>
</html>
This simplifies the function but may be less readable for more complex HTML structures.
The current way I usually do for my small projects is by defining a class to use a context for the component. For example, I could define a class called `Header` with functions like `renderMetatags()`, `renderScripts()`, `renderTitle($title)`, etc. Below there is one example:
class Footer {
public static function render($title) {
?>
<footer><?= $title ?></footer>
<?php
}
}
<html>
<body>
<?php Footer::render("My Website"); ?>
</body>
</html>
We can also use objects to render HTML with this concept, to avoid defining static methods:
class Footer {
public $title;
public function __construct($title) {
$this->title = $title;
}
public function render() {
?>
<footer><?= $this->title ?></footer>
<?php
}
}
<html>
<body>
<?php new Footer("My Website")->render(); ?>
</body>
</html>
But the way above looks too complex for this little necessity.
My Questions:
Is there an official or widely accepted **term** for this approach in native PHP (similar to "macros" in Flask/Jinja2)?
Are there any downsides or performance issues when using functions for rendering HTML components instead of `include`?
What are the best practices for creating reusable components in PHP **without using template libraries**?
I appreciate any insights or recommendations from experienced PHP developers!