Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to return html from php function?

Tags:

html

php

So I asked a similar question earlier and I'm only more confused now, so I'll ask it in a different way...

What I'm trying to do is abstract my php and put the bits of html, used in my validator as error messages, into functions that return the html to the spot where they are needed in the page.

What I have right now is:

<section>
<?php 
if($errMsg)
{
    errMsg();
}
?>
</section>

<?php
function errMsg()
{
       ?>
       <section>
           <p>O crap!  There was an error</p>
       </section>
       <?php
}
?>

But in my previously mentioned question, I was told doing it this way is a 'dirty hack' and its better to use return in situations like this. But to use return I'd need to assign all of the returning html to a var and to do that I would need to put the html in a string. I'd rather avoid putting more than two lines of html in a string because of the pain in the butt number of quotes needed to do so.

So I'm thinking I either use the heredoc syntax or ob_start/ob_get_clean functions. What I'd like to know is.

1 Do I even need to bother with abstracting my code like this?
2 If so, which way is the best practices way to do it? And/Or
3 Should I just give up on web development and go back to pizza delivery? :-\

like image 324
Matt Whitehead Avatar asked Aug 07 '12 08:08

Matt Whitehead


1 Answers

1: You don't need to, but you can if it's done properly.

2: To do this, i recommend you to use the EOF in your PHP error func, it looks like this :

function errMsg()
{
       $error = <<<EOF 
<section>
<p>O crap!  There was an error</p>
</section>
EOF;
}
like image 96
PoulsQ Avatar answered Oct 04 '22 04:10

PoulsQ