每个人都会遇到语法错误。即使是经验丰富的程序员也会出现拼写错误。对于新人来说,这只是学习过程的一部分。然而,通常很容易解释如下错误消息:
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版本不兼容造成的,因此请根据平台设置检查供应商的要求。
意外的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_IF
意想不到的T_ELSEIF
意想不到的T_ELSE
意想不到的T_ENDIF
条件控件块if、elseif和else遵循一个简单的结构。当你遇到语法错误时,很可能只是无效的块嵌套→缺少{花括号}——或者多了一个。
Missing { or } due to incorrect indentation
Mismatched code braces are common to less well-formatted code such as:
if((!($opt["uniQartz5.8"]!=$this->check58)) or (empty($_POST['poree']))) {if
($true) {echo"halp";} elseif((!$z)or%b){excSmthng(False,5.8)}elseif (False){
If your code looks like this, start afresh! Otherwise it's unfixable to you or anyone else. There's no point in showcasing this on the internet to inquire for help.
You will only be able to fix it, if you can visually follow the nested structure and relation of if/else conditionals and their { code blocks }. Use your IDE to see if they're all paired.
if (true) {
if (false) {
…
}
elseif ($whatever) {
if ($something2) {
…
}
else {
…
}
}
else {
…
}
if (false) { // a second `if` tree
…
}
else {
…
}
}
elseif (false) {
…
}
Any double } } will not just close a branch, but a previous condition structure. Therefore stick with one coding style; don't mix and match in nested if/else trees.
Apart from consistency here, it turns out helpful to avoid lengthy conditions too. Use temporary variables or functions to avoid unreadable if-expressions.
IF cannot be used in expressions
A surprisingly frequent newcomer mistake is trying to use an if statement in an expression, such as a print statement:
⇓
echo "<a href='" . if ($link == "example.org") { echo …
Which is invalid of course.
You can use a ternary conditional, but beware of readability impacts.
echo "<a href='" . ($link ? "http://yes" : "http://no") . "</a>";
Otherwise break such output constructs up: use multiple ifs and echos.
Better yet, use temporary variables, and place your conditionals before:
if ($link) { $href = "yes"; } else { $href = "no"; }
echo "<a href='$href'>Link</a>";
Defining functions or methods for such cases often makes sense too.
Control blocks don't return "results"
Now this is less common, but a few coders even try to treat if as if it could return a result:
$var = if ($x == $y) { "true" };
Which is structurally identical to using if within a string concatenation / expression.
But control structures (if / foreach / while) don't have a "result".
The literal string "true" would also just be a void statement.
You'll have to use an assignment in the code block:
if ($x == $y) { $var = "true"; }
Alternatively, resort to a ?: ternary comparison.
If in If
You cannot nest an if within a condition either:
⇓
if ($x == true and (if $y != false)) { ... }
Which is obviously redundant, because the and (or or) already allows chaining comparisons.
Forgotten ; semicolons
Once more: Each control block needs to be a statement. If the previous code piece isn't terminated by a semicolon, then that's a guaranteed syntax error:
⇓
$var = 1 + 2 + 3
if (true) { … }
Btw, the last line in a {…} code block needs a semicolon too.
Semicolon too early
Now it's probably wrong to blame a particular coding style, as this pitfall is too easy to overlook:
⇓
if ($x == 5);
{
$y = 7;
}
else ←
{
$x = -1;
}
Which happens more often than you might imagine.
When you terminate the if () expression with ; it will execute a void statement. The ; becomes a an empty {} of its own!
The {…} block thus is detached from the if, and would always run.
So the else no longer had a relation to an open if construct,
which is why this would lead to an Unexpected T_ELSE syntax error.
Which also explains a likewise subtle variation of this syntax error:
if ($x) { x_is_true(); }; else { something_else(); };
Where the ; after the code block {…} terminates the whole if
construct, severing the else branch syntactically.
Not using code blocks
It's syntactically allowed to omit curly braces {…} for code blocks in if/elseif/else branches. Which sadly is a syntax style very common to unversed coders. (Under the false assumption this was quicker to type or read).
However that's highly likely to trip up the syntax. Sooner or later additional statements will find their way into the if/else branches:
if (true)
$x = 5;
elseif (false)
$x = 6;
$y = 7; ←
else
$z = 0;
But to actually use code blocks, you do have to write {…} them as such!
Even seasoned programmers avoid this braceless syntax, or at least
understand it as an exceptional exception to the rule.
Else / Elseif in wrong order
One thing to remind yourself is the conditional order, of course.
if ($a) { … }
else { … }
elseif ($b) { … }
↑
You can have as many elseifs as you want, but else has to go last. That's just how it is.
Class declarations
As mentioned above, you can't have control statements in a class declaration:
class xyz {
if (true) {
function ($var) {}
}
You either forgot a function definition, or closed one } too early in such cases.
Unexpected T_ELSEIF / T_ELSE
When mixing PHP and HTML, the closing } for an if/elseif must be in the same PHP block <?php ?> as the next elseif/else. This will generate an error as the closing } for the if needs to be part of the elseif:
<?php if ($x) { ?>
html
<?php } ?>
<?php elseif ($y) { ?>
html
<?php } ?>
The correct form <?php } elseif:
<?php if ($x) { ?>
html
<?php } elseif ($y) { ?>
html
<?php } ?>
This is more or less a variation of incorrect indentation - presumably often based on wrong coding intentions.
You cannot mash other statements inbetween if and elseif/else structural tokens:
if (true) {
}
echo "in between"; ←
elseif (false) {
}
?> text <?php ←
else {
}
Either can only occur in {…} code blocks, not in between control structure tokens.
This wouldn't make sense anyway. It's not like that there was some "undefined" state when PHP jumps between if and else branches.
You'll have to make up your mind where print statements belong to / or if they need to be repeated in both branches.
Nor can you part an if/else between different control structures:
foreach ($array as $i) {
if ($i) { … }
}
else { … }
There is no syntactic relation between the if and else. The foreach lexical scope ends at }, so there's no point for the if structure to continue.
T_ENDIF
If an unexpected T_ENDIF is complained about, you're using the alternative syntax style if: ⋯ elseif: ⋯ else: ⋯ endif;. Which you should really think twice about.
A common pitfall is confusing the eerily similar : colon for a ; semicolon. (Covered in "Semicolon too early")
As indentation is harder to track in template files, the more when using the alternative syntax - it's plausible your endif; does not match any if:.
Using } endif;
is a doubled if-terminator.
While an "unexpected $end" is usually the price for a forgotten closing } curly brace.
Assignment vs. comparison
So, this is not a syntax error, but worth mentioning in this context:
⇓
if ($x = true) { }
else { do_false(); }
That's not a ==/=== comparison, but an = assignment. This is rather subtle, and will easily lead some users to helplessly edit whole condition blocks. Watch out for unintended assignments first - whenver you experience a logic fault / misbeheviour.
One more reason to occurrence of these errors is unexpected whitespace like similar characters with-in code, the code lines seems to be perfect, but they contains some specific characters which are similar to break line or whitespace or tab but they not get parsed by the parser.
I face this issue when I try to put some code from webpage to the code editor by simply copy paste, I saw this error with array definition. everything was looking right in array definition. I can't sort out right error, finally I define this array in single line, then error was gone. then again I try to make that definition multiple like but manually adding break(Enter) for each array element and saved the file this time no parsing error by editor and also no error while running it.
For Example I faced issue with this snippet which was on one blog, actually can't post those snippets ,cause stack overflow already knows the problem with code.
然后在解决它之后,我的工作片段是,它看起来类似于一个显示解析错误
语法错误,意外的“auth”(T_CONSTANT_ENCAPSED_STRING),期待']'
public $aliases = [
'csrf'=> \CodeIgniter\Filters\CSRF::class,
'toolbar'=> \CodeIgniter\Filters\DebugToolbar::class,
'honeypot'=> \CodeIgniter\Filters\Honeypot::class,
'auth' => \App\Filters\Auth::class,
];