Is it a bad practice to write HTML markup using only PHP echo statements?
There is a guy at work that pretty much writes all of his html markup by using echo statements. It looks reall开发者_开发技巧y clean and I like it a lot, but I remember hearing it is a bad practice considering it becomes a little much when you have to write large quantities of markup. What is the best practice?
Alright given the answers, I felt I should put in my 2 cents.
First up, it depends on the project. Me, personally, I use PHP as my template engine, and not a 3rd party. So I store my view logic in a "template" which is just php markup, which does use a few echos, but the echo statements just echo relevant data and not html code. Breaking in and out of PHP is not bad practice, if done correctly.
Having said that, it is much easier to manipulate HTML in a "template" file where the HTML is on it's own without having to worry about quotes (I know heredoc solves this problem, but it is kind of hard to do a foreach loop inside of a heredoc to display data). So my suggestion is just make a template folder / file for your view logic and use the short open tags, if you want to enable them / risk a client not having them enabled or use the <?php echo $data; ?>
to echo out your data in that file and include it when needed.
Sorry if this sounds confusing. But that is my preferred method, as having 10 echos that just display data vs 100 echos that display html and data looks nicer and is easier to maneuver / debug in my opinion.
Unless you have hundreds of lines of markup, I think that this is a micro-optimization. That is to say that a HEREDOC
, echo
, print
, or between PHP
tags doesn't really matter.
In the end, it boils down to what's easiest for you or your team to maintain.
This is not necessaryly bad practice. As long is your code is readable, do it this way.
If your project grows larger I might however suggest using a template engine (for example smarty.net).
I always read/heard that it's more efficient to throw out markup from PHP than to switch into and out of the preprocessor.
After all, that's what HEREDOCs are for. A TON of echo statements in a row is probably not as good a plan as one on a larger string.
I think the best practice is to simplify your code. If you have a large number of the Echo statements that can possibly be reused pull them out into a separate PHP file and use php require statement to include that common code so the main file you are looking at is simpler. Even if the can't be reused, but that they are static and should not change, pull them out. No need to clutter you page with information that is just noise.
I have all my html code inside different echo's and I find no problem whatsoever with it.
It sounds like a bad practice if you consider that someday you might want to change technologies (like from php to asp.net or ruby on rails). Seems like Seperation of Concerns is thrown out the window.
精彩评论