Page 1 of 1
PHP function - switching back and forth from HTML
Posted: Thu Jun 24, 2010 11:23 am
by paulstanely45
Hey Everybody,
This is probably a bit more of a technical question on how PHP itself works, but I was wondering if someone had an answer.
I have many a time seen, and used, functions that look like this:
Code: Select all
<?php
function show_form() { ?>
<form method="post">
<input type="text" value="somevalue" />
</form>
<?php
}
?>
Switching back and forth between PHP and HTML to make a function that can display HTML easily.
I don't understand how this works, wouldn't closing the PHP tag just make PHP wait till the tag opens again, negating any sort of content in the middle? This isn't the case obviously, can anyone explain why?
Re: PHP function - switching back and forth from HTML
Posted: Thu Jun 24, 2010 11:33 am
by ell0bo
It defined the content for that function, and when you turn off PHP it doesn't just run the HTML in the middle of it.
Basically, think of it translating to this...
function show_form() {
echo <<<HTML
<form method="post">
<input type="text" value="somevalue" />
</form>
HTML;
}
Basically, any code that is not in the php tags can be translated to an echo.
Re: PHP function - switching back and forth from HTML
Posted: Thu Jun 24, 2010 12:36 pm
by impressthenet
3 cheers for heredoc notation. heredoc is your friend!
Re: PHP function - switching back and forth from HTML
Posted: Wed Sep 08, 2010 11:04 am
by paulstanely45
what about in an instance like
Code: Select all
<?php
if(true) { ?>
<form id="1">
</form>
<?php } else { ?>
<form id="2">
</form>
<?php } ?>
I guess I don't really grap the technical aspect of it. What is the parser doing exactly?
Re: PHP function - switching back and forth from HTML
Posted: Wed Sep 08, 2010 11:08 am
by bradbury
its the exact same thing just use the echo then type your HTML in quotes
and your good to go
What happens is the php runs through the code and notices that it has to print out whatever is in the quotations of the echo call and it just so happens that it is html.
Re: PHP function - switching back and forth from HTML
Posted: Wed Sep 08, 2010 12:05 pm
by ell0bo
heredoc can be broken up
$html = <<<HTML
<form id='whatever'>
<span>
HTML;
if ( $iThink ){
$html .= 'I Am';
}else{
$html .= 'Guess I Am Not';
}
$html .= <<<HTML
</span>
</form>
HTML;
The main thing to realize, what's in PHP scope and what's being translated as base html. Anything inside the <?php ?> tags is php, otherwise it's considered just base html.
So when you're doing the
if ( true ){
?>
this is html
<?php
}else{
// this is inside the php scope
?>
this is other html
<?php
}
I find it cleaner to use here doc for that though, i think those PHP tags are nasty and switching in and out can give you weird white space in your code, and IE6 can be fun with that sometimes.
so... I just keep it all inside the PHP scope and utilize heredocs. That way also you can use $someVar in your heredoc to output a variable.