两个分离的PHP选择器之间的HTML包含if语句 2.
在这段代码中,我希望显示两个分离的PHP选择器之间的HTML包含if语句 2.,php,html,if-statement,rendering,Php,Html,If Statement,Rendering,在这段代码中,我希望显示div,因为它只是php之外的html,但事实并非如此。它是php的一部分 这是一个bug还是PHP的工作方式?不,这就是PHP的工作方式。括号内的任何内容都将被视为if语句内的内容,即使它位于php标记之外。您试图输出的内容都不会显示在屏幕上 你在“说”: 2. 或者另一种写作方式是 <?php if(1 == 2){ echo 1; ?> <div>2</div> <?php echo 3; }
div
,因为它只是php之外的html,但事实并非如此。它是php的一部分
这是一个bug还是PHP的工作方式?不,这就是PHP的工作方式。括号内的任何内容都将被视为if语句内的内容,即使它位于php标记之外。您试图输出的内容都不会显示在屏幕上 你在“说”:
2.
或者另一种写作方式是
<?php
if(1 == 2){
echo 1; ?>
<div>2</div>
<?php echo 3;
}
?>
2
这从来都不是真的,所以没有什么可以展示的
也许这就是你想要实现的目标:
<?php
if(1 == 2){
echo 1;
?><div>2</div><?php
echo 3;
}
?>
if(1==2){
回声1;
}
回声“2”;
如果(1==2){
回声3;
}
//产出:2
重要的是要记住,PHP是由服务器按照编写的顺序进行评估的,大括号告诉PHP服务器将作为一个单元进行评估,如果,则决定发送什么(例如HTML输出)。
可以这样考虑
if(1==2){
echo 1;
}
echo '<div>2</div>';
if(1==2){
echo 3;
}
// output: <div>2</div>
这允许做一些事情。首先,这意味着您可以运行复杂的过程来决定是否应该发送数据。以下面的例子为例
<?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将对该语句进行求值,如果该语句为真(您已登录),那么您将获得大括号中的内容(安全信息),否则它就好像它从未存在过一样
这是许多PHP框架使用模板系统的原因之一,这样您就可以在更直观的结构中工作,将代码的服务器评估部分保留在另一个文件中直到HTML输出后,您才终止if
块,有什么问题吗?@Marty我希望它将HTML部分从PHP中处理出来,因此,我首先echo 1
,然后显示html,然后echo 3
,以防语句为真。如果statment为false,则只显示html,但现在它就像是在php中回显html。我认为,通过将php分成两部分,html将被视为一个html
代码,而不是php
的一部分。它在读取脚本时都会呈现(被“合并”为html)。php不会因为脚本暂时离开php(?>
)而被“忽略”。AXAI它被视为html,但在if语句中,因此它仅在if语句为true时才会显示
<?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>