PHP 中出现意外的 T_ELSE 错误

发布于 2024-08-29 03:16:52 字数 1470 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

分分钟 2024-09-05 03:16:52

if 语句末尾有 ;

错误原因:

if(...) ;
{
...
}

不会导致任何语法错误,因为 if 的正文为空,并且以下块< em>总是被执行。但

if(...) ;
{
  // blk A
} else {
...
}

会导致 Unexpected else 语法错误,因为 if 和之前一样有空的主体,后面跟着另一个块 blk A ,它不是 if 的主体。现在,当在块后面找到 else if 时,它无法与任何导致此错误的 if 匹配。如果我们用语句代替块,也会发生同样的情况:

if(...) ;
 do_something;
else {
...
}

There are ; at the end of if statements.

Cause of error:

if(...) ;
{
...
}

Will not cause any syntax error as the body of if is empty and the following block always gets executed. But

if(...) ;
{
  // blk A
} else {
...
}

will cause Unexpected else syntax error because the if as before has empty body and is followed by another block blk A which is not if's body. Now when an else if found after the block it cannot be matched with any if causing this error. The same would happen if we'd statement(s) in place of a block:

if(...) ;
 do_something;
else {
...
}
秋心╮凉 2024-09-05 03:16:52

尝试:

$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/MSIE/i", $agent)) {
  $result = "You are using Microsoft Internet Explorer";
} else if (preg_match("/Mozilla/i", $agent)) {
  $result = "You are using Mozilla firefox";
} else {
  $result = "you are using $agent";
}

echo $result;

两件事:

  1. if 子句末尾有一个分号。这意味着后续的左大括号是始终执行的本地块。这导致了一个问题,因为后来您有一个 else 语句没有附加到 if 语句;

  2. 执行 "$agent" 是不必要的,也不建议这样做。只需传入 $agent

Try:

$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/MSIE/i", $agent)) {
  $result = "You are using Microsoft Internet Explorer";
} else if (preg_match("/Mozilla/i", $agent)) {
  $result = "You are using Mozilla firefox";
} else {
  $result = "you are using $agent";
}

echo $result;

Two things:

  1. You had a semi-colon at the end of your if clauses. That means the subsequent opening brace was a local block that is always executed. That caused a problem because later you had an else statement that wasn't attached to an if statement; and

  2. Doing "$agent" is unnecessary and not recommended. Simply pass in $agent.

删除包含“if”的行末尾的分号。

remove the semi-colons from the end of the lines with "if" in them.

老旧海报 2024-09-05 03:16:52

为什么这里有分号? if (preg_match("/MSIE/i", "$agent")); 此处 else if (preg_match("/Mozilla/i", "$agent"));< /代码>

Why do you have a semicolon here? if (preg_match("/MSIE/i", "$agent")); and here else if (preg_match("/Mozilla/i", "$agent"));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文