在 IF 内使用带大括号的 IF 而无需

Using IF with curly brackets within IF without

我有一些代码,我试图在彼此之间使用不同的 ifs,但我 运行 遇到了问题。我制作了这个测试代码来显示问题:

<?php
$test = 'lol';
if ($test == 'wat') :
    if (!empty($_GET['wat'])) {
        echo 'well';
    }
elseif ($test == 'lol') :
    echo 'loool';
endif;
die();
?>

这将 return 这个错误:

解析错误:语法错误,第 7 行 /var/www/domain.com/public_html/test.php 中的意外“:”

但这只是在我添加 if (!empty($_GET['wat'])) { }

之后

问题是,我是不是做错了什么,或者不能在没有大括号的情况下使用 if 吗?

我不确定您要在替代 if 语法语句中使用基本 if 语法来完成什么,但您可能应该避免使用它。这有点不稳定,但以下语法工作正常:

$condition = "test";
$other = null;
if ($condition == "test") :
    if (isset($other))
        echo "Set";
    else
        echo "Not Set";
elseif ($condition == "something") :
    echo "Huh";
endif;

以上会回显 "Not Set",因为 $condition == "test" 为真,而 $other 未设置。

我认为你的示例缺少的是你的基本语法 if 语句的结束 else 语句(我知道这不是必需的,但在这种情况下似乎会导致问题)。将您的代码修改为:

$test = "lol";
if ($test == "wat") :
    if (!empty($_GET["wat"]))
        echo "well";
    else
        echo "Nothing";
elseif ($test == "lol") :
    echo "loool";
endif;

使其编译并且 运行 就好了。这很奇怪,但似乎有效。

希望能提供一些见解!

编辑

如果是多行,只需要在if语句里面加括号:

$test = "lol";
if ($test == "wat") :
  if (!empty($_GET["wat"])){
    echo "well";
    // Do something else
  } else {
    echo "Nothing";
    // More Stuff
  }
elseif ($test == "lol") :
  echo "loool";
endif;