2017-08-09 166 views
0
<?php if(1 == 2){echo 1; ?> 
    <div>2</div> 
<?php echo 3;} ?> 

在这段代码中,我预计div中显示,因为它仅仅是PHP之外的HTML,但事实并非如此。它作为php的一部分工作。HTML包含if语句

这是一个错误,或者它是如何工作的?

+0

你不终止'如果'阻止,直到您的HTML输出后,有什么问题? – Marty

+0

@Marty我期待它将PHP中的html部分处理掉,所以我首先回显1,然后显示html,然后在回声3为真的情况下回显3。并且只在显示的情况下显示html,但现在它就像在php中回显html一样。 – AXAI

回答

0

你试图输出的内容都不会让它进入屏幕。

你 “说”:

<?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> 
+0

我认为通过将php分成两部分,HTML将被视为只是一个“HTML”代码,而不是“PHP”的一部分。 – AXAI

+0

它读取脚本时都会呈现(以html形式“合并”)。 PHP不会因为脚本临时离开php而被“忽略”('?>')。 – mickmackusa

+0

AXAI将它视为html,但在if语句内,因此它只会在if语句为true时显示 – serakfalcon

0

没有这是PHP的工作原理。括号内的任何内容都将被视为在if语句中,即使它在php标签之外。

1

要记住,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框架使用模板系统,使您可以更直观结构工作的原因之一,留下码坐的服务器评价部分在另一个文件