<?php if(1 == 2){echo 1; ?>
<div>2</div>
<?php echo 3;} ?>
在這段代碼中,我預計div
中顯示,因爲它僅僅是PHP之外的HTML,但事實並非如此。它作爲php的一部分工作。HTML包含if語句
這是一個錯誤,或者它是如何工作的?
<?php if(1 == 2){echo 1; ?>
<div>2</div>
<?php echo 3;} ?>
在這段代碼中,我預計div
中顯示,因爲它僅僅是PHP之外的HTML,但事實並非如此。它作爲php的一部分工作。HTML包含if語句
這是一個錯誤,或者它是如何工作的?
你試圖輸出的內容都不會讓它進入屏幕。
你 「說」:
<?php
if(1 == 2){
echo 1; ?>
<div>2</div>
<?php echo 3;
}
?>
或另一種方式來寫的是...
<?php
if(1 == 2){
echo 1;
?><div>2</div><?php
echo 3;
}
?>
這是不正確的,因此沒有任何顯示。
也許這就是你想達到什麼目的:
if(1==2){
echo 1;
}
echo '<div>2</div>';
if(1==2){
echo 3;
}
// output: <div>2</div>
我認爲通過將php分成兩部分,HTML將被視爲只是一個「HTML」代碼,而不是「PHP」的一部分。 – AXAI
它讀取腳本時都會呈現(以html形式「合併」)。 PHP不會因爲腳本臨時離開php而被「忽略」('?>')。 – mickmackusa
AXAI將它視爲html,但在if語句內,因此它只會在if語句爲true時顯示 – serakfalcon
沒有這是PHP的工作原理。括號內的任何內容都將被視爲在if語句中,即使它在php標籤之外。
要記住,PHP是它是寫在訂單的服務器進行評估是很重要的,而括號告訴PHP服務器將if
作爲一個單位進行評估,然後確定發送的內容(例如,HTML輸出)。 可以考慮如下。
<?php
if (true) {
//everything in here relies on the above if statement.
//I can exit php to write in HTML or plain text,
//but it remains within the same bracket
}
?>
這允許一些事情。首先,這意味着您可以運行復雜的流程來決定是否應該發送數據。以下面的例子。
<?php
// Function ignored as one whole chunk until called
function check_user_login() {
// check user login and return true for logged in or false if not
}
// If statement checked, now calls the function.
if (check_user_login()) {
// If you are logged in, then it will evalute everything within these braces.
// The result includes printing what is outside the `php` tags.
?>
<div>Secure information that should only be sent if the user is logged in</div>
<?php
} // now exiting the braces, we will evaluate the rest in order
?>
<h1>My Website</h1>
的PHP將評估的聲明,如果這是真的(你登錄了),那麼你得到的是在大括號(安全信息),否則它就像它從來沒有存在過。
這是很多PHP框架使用模板系統,使您可以更直觀結構工作的原因之一,留下碼坐的服務器評價部分在另一個文件
你不終止'如果'阻止,直到您的HTML輸出後,有什麼問題? – Marty
@Marty我期待它將PHP中的html部分處理掉,所以我首先回顯1,然後顯示html,然後在回聲3爲真的情況下回顯3。並且只在顯示的情況下顯示html,但現在它就像在php中回顯html一樣。 – AXAI