簡體   English   中英

我可以在PHP的IF-ELSE語句中使用HTML代替echo嗎?

[英]Can i use HTML instead of echo in IF-ELSE statement in PHP?

if( $user->username == 'XYZ' )
{ 
echo "hello, XYZ";
}
else
{
echo "hello, guest";
}

在上面的代碼中, 如果IF語句為true ,我可以使用將執行的純HTML代碼而不是使用echo嗎?

是的,您可以這樣做:

if( $user->username == 'XYZ' ) 
{
?>
hello, XYZ
<?
} 
else
{
?>
hello, guest
<?
}

有時看起來更好,更簡單。 但是實際上,最好將php和html代碼放在不同的文件中(分開的邏輯,樣式和數據)。

if( $user->username == 'XYZ' )
{ ?>
<p>Hello <b><i>XYZ</i></b>
<?php }

else { ?>
<p>Hello <b><i>Guest</i></b>
<?php 
}

我希望你知道了。

當然,您可以通過關閉<?php ?>標簽直接編寫HTML。

<?php if( $user->username == 'XYZ') { ?>
   hello, XYZ<br>
<?php } ?>
<?php else { ?>
   hello, guest<br>
<?php } ?>

您當然也可以heredoc:

<?php
   $str = <<<FOO
This is a
demo message
FOO;

echo $str;
?>

但我不使用它,因為我將其與任何突出顯示的編輯器弄混了(它認為這是文本,我喜歡突出顯示的HTML)

我最喜歡的是這個,尤其是當我的輸出很大時:

<?php if( $user->username == 'XYZ') {
   include("user_template.php");
}
<?php else { ?>
   include("guest_template.php");
<?php } ?>

實際上只是渲染其中包含的HTML。

也可以這樣寫,多行可讀。

<?php if ($user->username == 'XYZ') : ?>
    Hello, XYZ
<?php else : ?>
    Hello, Guest
<?php endif; ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM