【问题标题】:Including an if statement inside an echo在 echo 中包含 if 语句
【发布时间】:2014-05-10 17:14:33
【问题描述】:
我正在呼应一些 HTML,并希望在其中包含一个 if 语句,但我不知道如何处理它:
echo '<li><a href="'.$category->getURL().'" style="text-decoration: none; if ($magentoCurrentUrl = $category->getURL()){ echo color:#fff; }" >'.$category->getName().'</a> </li>';
我想使用 if 语句为链接添加样式。
感谢您的帮助。谢谢。
【问题讨论】:
标签:
php
if-statement
echo
【解决方案1】:
在 echo 内部使用三元运算(true ? "dothis" : "doother"):
echo '<li><a href="'.$category->getURL().'" style="text-decoration: none;'.($magentoCurrentUrl == $category->getURL() ? 'color:#fff;' : '').'" >'.$category->getName().'</a> </li>';
三元运算公式基本是:
echo "something: ".(true ? "dothis" : "doother")
相当于
if (true) { echo "dothis": } else { echo "doother"; }
【解决方案2】:
为了防止出现带有内联逻辑的巨大echo 语句,我将包含一小段代码来确定style 属性值在您echo HTML 之前将是什么。
// build style attribute value
$style = 'text-decoration: none';
if ($magentoCurrentUrl = $category->getURL()) {
$style = $style . '; color: #fff;'
}
// output HTML
echo '<li><a href="'.$category->getURL().'" style="$style" >'.$category->getName().'</a> </li>';
您甚至可以冒险添加一个 getStyle() 方法,该方法可以为您的 $category 对象构建该样式。然后你就得到了一些干净的代码:
echo '<li><a href="'.$category->getURL().'" style="'.$category->getStyle().'">'.$category->getName().'</a> </li>';
【解决方案3】:
这是一种干净的方法。如果你想用可读的 HTML 代码传递 $variables,请在 echo 语句中使用双引号。
if ($magentoCurrentUrl = $category->getURL())
{
$color="color:#fff";
}
else {
$color=" ";
}
echo "<li><a href='$category->getURL()' style='text-decoration: none;$color' >$category->getName()</a> </li>";