6

我对 PHP 相当陌生。我在 3 周前开始学习它。我在 StackOverflow、Google 或 Youtube 上找不到这个问题的答案。对此的PHP 文档让我感到困惑。继续这个问题,PHP 代码与 HTML 混合是如何工作的?

<?php if (something) { ?>
    <p>Hello</p>
<?php } ?>

p 元素只会在某些东西具有真实值时显示,这是怎么回事?...我确信 PHP 引擎忽略了代码块外部发生的事情(例如 <?php ?>)并且只解析里面发生了什么。

下面的代码被 PHP 引擎正常解析并发送到浏览器,而不影响任何 HTML 元素(即使它明显位于 2 个代码块之间)。

<?php echo $something; ?>
<p>Hello</p>
<?php echo $something; ?>

我希望我不会因为问这个问题而被激怒,因为很多人似乎在十分之一秒内就能理解它是如何工作的。

PS我很早就在聊天中问了这个问题,并认为我理解正确,但是当我去实施它时,我的想法仍然是,这到底是如何工作的?对我来说,这似乎是某种黑客行为。

4

5 回答 5

5

现在轻松了。绝对需要一个 php 教程让您从 http://www.tizag.com/phpT/开始

这是你在做什么:

<?php 
//Anything inside me php processes
if($something)
{
    echo "<p>something</p>";
}
//About to stop processing in php
?>
<p>Anything outside of the php statement above will just be printed to the dom</p>

快速说明:将 PHP 与 HTML 分开是一种很好的做法

<?php if ($something) { ?>  <-- where is the other {
<p>Hello</p>
<?php } ?> <-- oh I see it.
于 2012-08-20T04:30:09.043 回答
3

在您的第一个示例中,<p>Hello</p>当且仅当“某事”返回 true 时,才会呈现确实如此。

如果您使用 ?> 关闭 php 标签,但执行“未关闭” if (blah) { ...,则 PHP 引擎会理解您的需求并相应地执行。

为什么?

PHP 引擎一直“等待”,直到使用 } 关闭执行,然后评估最终结果,浏览器继续执行以下行。

显然,如果你省略最后的 },你会看到一些错误,这告诉你 PHP 期望你完成你开始的事情,而你没有

于 2012-08-20T04:35:30.740 回答
1

php 和 html 都是内联解析的。因此,当它向下移动您的脚本时,它将在标签内运行 php 脚本,并按照它们放置的顺序显示 html。例如:

<? $someVar = "someVar string value"; ?>
<h1>This is a title</h1>
<? if(1 == 1){?>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<? } ?>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: <?=$someVar;?></p> // <?= is a short hand for echo

这将显示为:

<h1>This is a title</h1>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: someVar string value</p>

基本上只需将其视为服务器读取您的脚本并解析它所看到的任何内容。如果有 html,它将显示它,如果有 php 进行某种计算然后吐出 html,它将显示吐出的 html。

于 2012-08-20T04:32:24.157 回答
0

您可以使用 php 代码块在 HTML 中的任何位置编写 php 代码

<?php echo "whatever " ?> 

或者

<?php echo "<h1>Here everything will displayed in h1 </h1> "; ?>

如果您使用控制结构(if、switch等),那么它的行为将与所有其他语言一样,这意味着如果某事为,那么它将执行之间编写的部分 { }

因此,如果您在 if 条件中写入未定义的变量,那么它将不会执行代码块,因为未定义的变量被视为错误条件。

另外,您可以通过以下方式检查任何变量值var_dump($variable)

于 2012-08-20T04:33:28.707 回答
0

PHP控制结构的替代语法

<!DOCTYPE html>
...
<div>
<?php if ( the_thing === true ) : ?>
    <p>The thing is true! \o/</p>
<?php else if ( the_other_thing === true ) : ?>
    <p>The other thing is true! meh</p>
<?php else : ?>
    <p>Nothing is true :-(</p>
<?php endif; ?>
</div>
...
于 2017-05-10T22:39:50.460 回答