PHP 中的意外 T_ELSE 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2642512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unexpected T_ELSE error in PHP
提问by Hymansta
I am working on an example from a php book and am getting an error on line 8 with this code
我正在研究一本 php 书中的一个例子,并且在第 8 行出现了一个错误,这个代码是
<?php
$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;
?>
回答by codaddict
There are ;at the end of ifstatements.
有;在结束if发言。
Cause of error:
错误原因:
if(...) ;
{
...
}
Will notcause any syntax error as the body of ifis emptyand the following block alwaysgets executed. But
会不会造成任何语法错误,因为身体if是空的和下面的块总是被执行。但
if(...) ;
{
// blk A
} else {
...
}
will cause Unexpected elsesyntax error because the ifas before has empty body and is followed by another block blk Awhich is not if's body. Now when an elseif found after the block it cannotbe matched with any ifcausing this error. The same would happen if we'd statement(s) in place of a block:
将导致Unexpected else语法错误,因为ifas before 的主体为空,后面是另一个blk A不是 if 主体的块。现在,当else在块之后找到 if时,它无法与if导致此错误的任何内容匹配。如果我们用statement(s)代替块,也会发生同样的情况:
if(...) ;
do_something;
else {
...
}
回答by cletus
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:
两件事情:
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
elsestatement that wasn't attached to anifstatement; andDoing
"$agent"is unnecessary and not recommended. Simply pass in$agent.
您的 if 子句末尾有一个分号。这意味着随后的左大括号是一个始终执行的本地块。这导致了一个问题,因为后来你有一个
else没有附加到if声明的声明;和这样做
"$agent"是不必要的,不推荐。简单的传入$agent。
回答by timdev
remove the semi-colons from the end of the lines with "if" in them.
删除带有“if”的行末尾的分号。
回答by brianreavis
Why do you have a semicolon here? if (preg_match("/MSIE/i", "$agent"));and here else if (preg_match("/Mozilla/i", "$agent"));
为什么这里有一个分号?if (preg_match("/MSIE/i", "$agent"));和这里else if (preg_match("/Mozilla/i", "$agent"));

