I've programmed for many years now in c++/c/python but never did a project in PHP, which I will be doing soon.
1- I find the usage of echo to be somewhat annoying, especially for printing long stuff. For example, if I have a function which wants to echo a redundant part of a website, such as the header or a nav menu, what approach would be better.
<?php
function PrintHeader() {
[some php stuff, mysql queries, etc]
?>
some HTML code
more HTML code
<?php
[some closing php stuff]
}
?>
Is it better than
<?php
function PrintHeader() {
[some php stuff, mysql queries, etc]
echo 'some HTML code'
echo 'more HTML code'
[some closing php stuff]
}
?>
I find somewhat the first approach to be, to me, simpler, because you can modify the HTML code more easily without the echos. I tested it, it works, but is it a good approach? Is it valid?
2- Is it considered a good programming practice to use a function to echo a redundant part of a website, rather than copy/pasting the redundant code accross all PHP files?
These questions might sound obvious to some, but I have not much experience about code management in PHP. I always liked to reduce code redundancy as much as possible; it's easier to maintain.
Traditionally, this kind of thing is achieved in PHP by "requiring" a file that contains the content you need. e.g.
header.php:
<div>some html</div>
Your main file:
<?php
require 'header.php';
?>
This removes much of the need to embed HTML within your PHP. However, a more modern approach is to use a templating language, which allows you to house your HTML, along with simple display logic like branching and loops, outside of your PHP code entirely. Have a look at http://www.phptherightway.com/#templating for some more advice on both approaches. I'd strongly recommend you read all of phptherightway.com, in fact - it doesn't take long and will probably answer a lot of other questions you might have.
first of all, nowadays people often use template files which are later parsed by PHP. Often are template languages like Twig for example used.
its more user preference in my opinion, but I definetly prefer the 1st variant because its a lot more readable :).
You should definetly put redundant parts of your website into a template and just include it if you need it :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With