Skip to content Skip to sidebar Skip to footer

Outputting Html With Echo Considered Bad Practice In Php?

In PHP, I'm using an if statement to identify whether a user is logged in or not, and depending on the result, displaying the main menu (if logged in) or a 'you need to login' mess

Solution 1:

I consider it to be bad practice. Not sure about what anyone else thinks. For one thing, it looks terrible in text editors with syntax highlighting, then you have to worry about escaped strings, etc.

This is how I do it:

<div><?if ($_SESSION['loggedIn'] === 1): ?><divid="main">Main Menu stuff goes here</div><?else: ?><divid="main">Please log in...</div><?endif?></div>

You can hop out of the PHP tags and use straight up HTML. There are pros and cons to doing it this way. I like it way better than echoing stuff out. Other options would be to render new views into those areas based on the results of the if statements. Lots of possibilities, but the above is just one way to make that a little cleaner and (I think) better.

Solution 2:

There's nothing wrong with echo for html, when used in moderation. Just don't use it for long multi-line blocks. You'll invariably end up with some ugly construct requiring escaping and whatnot, which makes things even uglier to read.

If the html you're outputting is "static" (no variables to insert), then consider breaking OUT of php mode (?>) and simply dumping the html as is. If you do need to insert variables, then consider using a HEREDOC, which act like a double-quoted string, but without the quotes.

Solution 3:

Why not write it like this?

<?phpif($_SESSION['loggedIn'] == 1): ?><divid='main'>MAIN MENU stuff goes here</div><?phpelse: ?><divid='main'>Please login...</div><?phpendif; ?>

Using the alternative control structures seperates your markup from your code a bit more.

Solution 4:

<?phpif (condition) { ?><div> 
        some stuff
     </div><?php } ?>

The beauty of PHP is that you can do this.

Solution 5:

If your project gets to a reasonable size, there's essentially no way around a clean separation of presentational elements and program logic, just for the sake of maintainability and scalability. So what you're doing in your current code doesn't really matter; in the long run, you should look into a clean design approach from the outset.

There are many existing solutions, usually involving some sort of layout templates which are loaded by the code.

Post a Comment for "Outputting Html With Echo Considered Bad Practice In Php?"