每个人都会遇到语法错误。即使是经验丰富的程序员也会出现拼写错误。对于新人来说,这只是学习过程的一部分。然而,通常很容易解释如下错误消息:
PHP解析错误:语法错误,在index.php第20行中出现意外的“{”
意想不到的符号并不总是真正的罪魁祸首。但是行号给出了从哪里开始查找的大致概念。
总是查看代码上下文。语法错误通常隐藏在前面提到的或前面的代码行中。将您的代码与手册中的语法示例进行比较。
但并不是所有情况都是一样的。但是有一些通用的步骤可以解决语法错误。
本文总结了常见的陷阱:
Unexpected T_STRING
Unexpected T_VARIABLE Unexpected '$varname' (T_VARIABLE)
Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE
Unexpected $end
Unexpected T_FUNCTION…
Unexpected {Unexpected }Unexpected (Unexpected )
Unexpected [Unexpected ]
Unexpected T_IF Unexpected T_FOREACH Unexpected T_FOR Unexpected T_WHILE Unexpected T_DO Unexpected T_PRINT Unexpected T_ECHO
Unexpected T_LNUMBER
Unexpected ?
Unexpected continue (T_CONTINUE)Unexpected continue (T_BREAK)Unexpected continue (T_RETURN)
Unexpected '='
Unexpected T_INLINE_HTML…
Unexpected T_PAAMAYIM_NEKUDOTAYIM…
Unexpected T_OBJECT_OPERATOR…
Unexpected T_DOUBLE_ARROW…
Unexpected T_SL…
Unexpected T_BOOLEAN_OR…
Unexpected T_BOOLEAN_AND…
Unexpected T_IS_EQUAL
Unexpected T_IS_GREATER_OR_EQUAL
Unexpected T_IS_IDENTICAL
Unexpected T_IS_NOT_EQUAL
Unexpected T_IS_NOT_IDENTICAL
Unexpected T_IS_SMALLER_OR_EQUAL
Unexpected <
Unexpected >
Unexpected T_NS_SEPARATOR…
Unexpected character in input: '\' (ASCII=92) state=1
Unexpected 'public' (T_PUBLIC) Unexpected 'private' (T_PRIVATE) Unexpected 'protected' (T_PROTECTED) Unexpected 'final' (T_FINAL)…
Unexpected T_STATIC…
Unexpected T_CLASS…
Unexpected 'use' (T_USE)
Unexpected T_DNUMBER
Unexpected , (comma)
Unpexected . (period)
Unexpected ; (semicolon)
Unexpected * (asterisk)
Unexpected : (colon)
Unexpected ':', expecting ',' or ')'
Unexpected & (call-time pass-by-reference)
Unexpected .
密切相关的参考文献:
这个错误在PHP中意味着什么?(运行时错误)
解析错误:语法错误,意外的T_XXX
解析错误:语法错误,意外的T_ENCAPSED_AND_WHITESPACE
解析错误:语法错误,意外的T_VARIABLE
这个符号在PHP中是什么意思?(语言标记)
这些“聪明”的引号对PHP毫无意义
And:
php.net上的PHP手册和它的各种语言标记
或者维基百科关于PHP的语法介绍。
最后是我们的php标签维基。
虽然Stack Overflow也欢迎新手程序员,但它主要针对的是专业编程问题。
回答每个人的编码错误和狭窄的拼写错误被认为是离题了。
因此,在发布语法修正请求之前,请花时间遵循基本步骤。
如果你仍然必须这样做,请展示你自己的解决方案,尝试修复,以及你对看起来或可能错误的思考过程。
如果您的浏览器显示错误消息,如“SyntaxError: illegal character”,那么它实际上不是php相关的,而是javascript语法错误。
供应商代码引起的语法错误:最后,考虑一下,如果语法错误不是由编辑代码库引起的,而是在外部供应商包安装或升级之后引起的,则可能是由于PHP版本不兼容造成的,因此请根据平台设置检查供应商的要求。
意想不到的(
现在,在过时的PHP版本中经常可以看到意外的[array括号]。短数组语法从PHP >= 5.4开始可用。旧的安装只支持array()。
$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
⇑
数组函数结果解引用同样不适用于旧的PHP版本:
$result = get_whatever()["key"];
⇑
这个错误在PHP中意味着什么?-“语法错误,意外的\[”显示了最常见和实用的解决方案。
不过,最好还是升级PHP安装。对于共享网络托管计划,首先要研究是否可以使用SetHandler php5 56-fcgi来启用新的运行时。
参见:
对函数result→进行解引用的PHP语法,从PHP 5.4开始可能
PHP语法错误,意外的“[”
数组的简写:是否存在像{}或[]这样的文字语法?
PHP 5.3.10 vs PHP 5.5.3语法错误
数组()和[]的区别
PHP数组语法解析错误
顺便说一下,如果你对老版本和慢版本的PHP很感兴趣的话,还有预处理器和PHP 5.4语法下转换器。
导致意外语法错误的其他原因
如果不是PHP版本不匹配,那么通常是一个简单的拼写错误或新手语法错误:
You can't use array property declarations/expressions in classes, not even in PHP 7.
protected $var["x"] = "Nope";
⇑
Confusing [ with opening curly braces { or parentheses ( is a common oversight.
foreach [$a as $b)
⇑
Or even:
function foobar[$a, $b, $c] {
⇑
Or trying to dereference constants (before PHP 5.6) as arrays:
$var = const[123];
⇑
At least PHP interprets that const as a constant name.
If you meant to access an array variable (which is the typical cause here), then add the leading $ sigil - so it becomes a $varname.
You are trying to use the global keyword on a member of an associative array. This is not valid syntax:
global $var['key'];
结束方括号
这种情况比较少见,但是终止数组[括号]也会出现语法错误。
同样,与)括号或}大括号不匹配是常见的:
函数foobar($a, $b, $c] {
⇑
或者试图结束一个没有数组的数组:
$var = 2];
这通常发生在多行和嵌套数组声明中。
$数组=[1,2,3],4(5、6 (7 [8][9 10]],11),12]],15);
⇑
如果是,请使用IDE进行括号匹配以查找任何过早的]数组闭包。至少使用更多的空格和换行来缩小范围。
意想不到的T_VARIABLE
一个“意外的T_VARIABLE”意味着有一个字面的$变量名,它不适合当前表达式/语句结构。
Missing semicolon
It most commonly indicates a missing semicolon in the previous line. Variable assignments following a statement are a good indicator where to look:
⇓
func1()
$var = 1 + 2; # parse error in line +2
String concatenation
A frequent mishap are string concatenations with forgotten . operator:
⇓
print "Here comes the value: " $value;
Btw, you should prefer string interpolation (basic variables in double quotes) whenever that helps readability. Which avoids these syntax issues.
String interpolation is a scripting language core feature. No shame in utilizing it. Ignore any micro-optimization advise about variable . concatenation being faster. It's not.
Missing expression operators
Of course the same issue can arise in other expressions, for instance arithmetic operations:
⇓
print 4 + 7 $var;
PHP can't guess here if the variable should have been added, subtracted or compared etc.
Lists
Same for syntax lists, like in array populations, where the parser also indicates an expected comma , for example:
⇓
$var = array("1" => $val, $val2, $val3 $val4);
Or functions parameter lists:
⇓
function myfunc($param1, $param2 $param3, $param4)
Equivalently do you see this with list or global statements, or when lacking a ; semicolon in a for loop.
Class declarations
This parser error also occurs in class declarations. You can only assign static constants, not expressions. Thus the parser complains about variables as assigned data:
class xyz { ⇓
var $value = $_GET["input"];
Unmatched } closing curly braces can in particular lead here. If a method is terminated too early (use proper indentation!), then a stray variable is commonly misplaced into the class declaration body.
Variables after identifiers
You can also never have a variable follow an identifier directly:
⇓
$this->myFunc$VAR();
Btw, this is a common example where the intention was to use variable variables perhaps. In this case a variable property lookup with $this->{"myFunc$VAR"}(); for example.
Take in mind that using variable variables should be the exception. Newcomers often try to use them too casually, even when arrays would be simpler and more appropriate.
Missing parentheses after language constructs
Hasty typing may lead to forgotten opening or closing parenthesis
for if and for and foreach statements:
⇓
foreach $array as $key) {
Solution: add the missing opening ( between statement and variable.
⇓
if ($var = pdo_query($sql) {
$result = …
The curly { brace does not open the code block, without closing the if expression with the ) closing parenthesis first.
Else does not expect conditions
⇓
else ($var >= 0)
Solution: Remove the conditions from else or use elseif.
Need brackets for closure
⇓
function() use $var {}
Solution: Add brackets around $var.
Invisible whitespace
As mentioned in the reference answer on "Invisible stray Unicode" (such as a non-breaking space), you might also see this error for unsuspecting code like:
<?php
⇐
$var = new PDO(...);
It's rather prevalent in the start of files and for copy-and-pasted code. Check with a hexeditor, if your code does not visually appear to contain a syntax issue.
另请参阅
搜索:意外T_VARIABLE
意想不到的“。”
如果您试图在不受支持的PHP版本中使用splat操作符(…),就会发生这种情况。
... 首次在PHP 5.6中可用来捕获函数的可变数量的参数:
function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
// This would print:
// I'D LIKE 6 APPLES
在PHP 7.4中,可以将它用于Array表达式。
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
意外的T_CONSTANT_ENCAPSED_STRING意外的t_encapsed_and_空白
T_CONSTANT_ENCAPSED_STRING和T_ENCAPSED_AND_WHITESPACE是指带引号的“字符串”字面量。
它们在不同的上下文中使用,但语法问题非常相似。t_encaged…警告出现在双引号的字符串上下文中,而T_CONSTANT…字符串经常在普通PHP表达式或语句中出错。
Incorrect variable interpolation
And it comes up most frequently for incorrect PHP variable interpolation:
⇓ ⇓
echo "Here comes a $wrong['array'] access";
Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted 'string', because it usually expects a literal identifier / key there.
More precisely it's valid to use PHP2-style simple syntax within double quotes for array references:
echo "This is only $valid[here] ...";
Nested arrays or deeper object references however require the complex curly string expression syntax:
echo "Use {$array['as_usual']} with curly syntax.";
If unsure, this is commonly safer to use. It's often even considered more readable. And better IDEs actually use distinct syntax colorization for that.
Missing concatenation
If a string follows an expression, but lacks a concatenation or other operator, then you'll see PHP complain about the string literal:
⇓
print "Hello " . WORLD " !";
While it's obvious to you and me, PHP just can't guess that the string was meant to be appended there.
Confusing string quote enclosures
The same syntax error occurs when confounding string delimiters. A string started by a single ' or double " quote also ends with the same.
⇓
print "<a href="' . $link . '">click here</a>";
⌞⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟
That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes.
Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.)
This is a good example where you shouldn't break out of double quotes in the first place. Instead just use proper \" escapes for the HTML attributes´ quotes:
print "<a href=\"{$link}\">click here</a>";
While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.
Missing opening quote
Equivalently are forgotten opening "/' quotes a recipe for parser errors:
⇓
make_url(login', 'open');
Here the ', ' would become a string literal after a bareword, when obviously login was meant to be a string parameter.
Array lists
If you miss a , comma in an array creation block, the parser will see two consecutive strings:
array( ⇓
"key" => "value"
"next" => "....",
);
Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting.
Function parameter lists
The same thing for function calls:
⇓
myfunc(123, "text", "and" "more")
Runaway strings
A common variation are quite simply forgotten string terminators:
⇓
mysql_evil("SELECT * FROM stuffs);
print "'ok'";
⇑
Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course.
HEREDOC indentation
Prior PHP 7.3, the heredoc string end delimiter can't be prefixed with spaces:
print <<< HTML
<link..>
HTML;
⇑
Solution: upgrade PHP or find a better hoster.
另请参阅
PHP中关联数组的插值(双引号字符串)
语法错误,意外的T_CONSTANT_ENCAPSED_STRING
语法错误,PHP中意外的T_CONSTANT_ENCAPSED_STRING
SQL查询中出现意外的T_CONSTANT_ENCAPSED_STRING错误
意想不到的T_IS_EQUAL
意想不到的T_IS_GREATER_OR_EQUAL
意想不到的T_IS_IDENTICAL
意想不到的T_IS_NOT_EQUAL
意想不到的T_IS_NOT_IDENTICAL
意想不到的T_IS_SMALLER_OR_EQUAL
意想不到的<
意想不到的>
比较运算符,如==,>=,===,!=,<>,!==和<=或<和>,主要应该只在表达式中使用,例如if表达式。如果解析器抱怨它们,那么通常意味着它们周围的paren不正确或不匹配()。
Parens grouping
In particular for if statements with multiple comparisons you must take care to correctly count opening and closing parenthesis:
⇓
if (($foo < 7) && $bar) > 5 || $baz < 9) { ... }
↑
Here the if condition here was already terminated by the )
Once your comparisons become sufficiently complex it often helps to split it up into multiple and nested if constructs rather.
isset() mashed with comparing
A common newcomer is pitfal is trying to combine isset() or empty() with comparisons:
⇓
if (empty($_POST["var"] == 1)) {
Or even:
⇓
if (isset($variable !== "value")) {
This doesn't make sense to PHP, because isset and empty are language constructs that only accept variable names. It doesn't make sense to compare the result either, because the output is only/already a boolean.
Confusing >= greater-or-equal with => array operator
Both operators look somewhat similar, so they sometimes get mixed up:
⇓
if ($var => 5) { ... }
You only need to remember that this comparison operator is called "greater than or equal" to get it right.
See also: If statement structure in PHP
Nothing to compare against
You also can't combine two comparisons if they pertain the same variable name:
⇓
if ($xyz > 5 and < 100)
PHP can't deduce that you meant to compare the initial variable again. Expressions are usually paired according to operator precedence, so by the time the < is seen, there'd be only a boolean result left from the original variable.
See also: unexpected T_IS_SMALLER_OR_EQUAL
Comparison chains
You can't compare against a variable with a row of operators:
⇓
$reult = (5 < $x < 10);
This has to be broken up into two comparisons, each against $x.
This is actually more a case of blacklisted expressions (due to equivalent operator associativity). It's syntactically valid in a few C-style languages, but PHP wouldn't interpret it as expected comparison chain either.
Unexpected > Unexpected <
The greater than > or less than < operators don't have a custom T_XXX tokenizer name. And while they can be misplaced like all they others, you more often see the parser complain about them for misquoted strings and mashed HTML:
⇓
print "<a href='z">Hello</a>";
↑
This amounts to a string "<a href='z" being compared > to a literal constant Hello and then another < comparison. Or that's at least how PHP sees it. The actual cause and syntax mistake was the premature string " termination.
It's also not possible to nest PHP start tags:
<?php echo <?php my_func(); ?>
↑
参见:
php T_IS_NOT_EQUAL错误
语法错误,意外的T_IS_EQUAL
返回语句的语法错误
http://forums.phpfreaks.com/topic/96891-parse-error-syntax-error-unexpected-t-is-not-identical-expecting-or/