每个人都会遇到语法错误。即使是经验丰富的程序员也会出现拼写错误。对于新人来说,这只是学习过程的一部分。然而,通常很容易解释如下错误消息:
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_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
意想不到的T_STRING
T_STRING有点用词不当。它不引用引用的“字符串”。这意味着遇到了原始标识符。这可以是空白的单词、剩余的CONSTANT或函数名、被遗忘的不带引号的字符串或任何纯文本。
Misquoted strings
This syntax error is most common for misquoted string values however. Any unescaped and stray " or ' quote will form an invalid expression:
⇓ ⇓
echo "<a href="http://example.com">click here</a>";
Syntax highlighting will make such mistakes super obvious. It's important to remember to use backslashes for escaping \" double quotes, or \' single quotes - depending on which was used as string enclosure.
For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within.
Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal " double quotes.
For lengthier output, prefer multiple echo/print lines instead of escaping in and out. Better yet consider a HEREDOC section.
Another example is using PHP entry inside HTML code generated with PHP:
$text = '<div>some text with <?php echo 'some php entry' ?></div>'
This happens if $text is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here
See also What is the difference between single-quoted and double-quoted strings in PHP?.
Unclosed strings
If you miss a closing " then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value:
⇓
echo "Some text", $a_variable, "and some runaway string ;
success("finished");
⇯
It's not just literal T_STRINGs which the parser may protest then. Another frequent variation is an Unexpected '>' for unquoted literal HTML.
Non-programming string quotes
If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren't what PHP expects:
$text = ’Something something..’ + ”these ain't quotes”;
Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example ”these is interpreted as a constant identifier. But any following text literal is then seen as a bareword/T_STRING by the parser.
The missing semicolon; again
If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:
⇓
func1()
function2();
PHP just can't know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one || or the other.
Short open tags and <?xml headers in PHP scripts
This is rather uncommon. But if short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration:
⇓
<?xml version="1.0"?>
PHP will see the <? and reclaim it for itself. It won't understand what the stray xml was meant for. It'll get interpreted as constant. But the version will be seen as another literal/constant. And since the parser can't make sense of two subsequent literals/values without an expression operator in between, that'll be a parser failure.
Invisible Unicode characters
A most hideous cause for syntax errors are Unicode symbols, such as the non-breaking space. PHP allows Unicode characters as identifier names. If you get a T_STRING parser complaint for wholly unsuspicious code like:
<?php
print 123;
You need to break out another text editor. Or an hexeditor even. What looks like plain spaces and newlines here, may contain invisible constants. Java-based IDEs are sometimes oblivious to an UTF-8 BOM mangled within, zero-width spaces, paragraph separators, etc. Try to reedit everything, remove whitespace and add normal spaces back in.
You can narrow it down with with adding redundant ; statement separators at each line start:
<?php
;print 123;
The extra ; semicolon here will convert the preceding invisible character into an undefined constant reference (expression as statement). Which in return makes PHP produce a helpful notice.
The `$` sign missing in front of variable names
Variables in PHP are represented by a dollar sign followed by the name of the variable.
The dollar sign ($) is a sigil that marks the identifier as a name of a variable. Without this sigil, the identifier could be a language keyword or a constant.
This is a common error when the PHP code was "translated" from code written in another language (C, Java, JavaScript, etc.). In such cases, a declaration of the variable type (when the original code was written in a language that uses typed variables) could also sneak out and produce this error.
Escaped Quotation marks
If you use \ in a string, it has a special meaning. This is called an "Escape Character" and normally tells the parser to take the next character literally.
Example: echo 'Jim said \'Hello\''; will print Jim said 'hello'
If you escape the closing quote of a string, the closing quote will be taken literally and not as intended, i.e. as a printable quote as part of the string and not close the string. This will show as a parse error commonly after you open the next string or at the end of the script.
Very common error when specifiying paths in Windows: "C:\xampp\htdocs\" is wrong. You need "C:\\xampp\\htdocs\\".
Typed properties
You need PHP ≥7.4 to use property typing such as:
public stdClass $obj;
意想不到的T_LNUMBER
令牌T_LNUMBER指向一个“长”/ number。
Invalid variable names
In PHP, and most other programming languages, variables cannot start with a number. The first character must be alphabetic or an underscore.
$1 // Bad
$_1 // Good
Quite often comes up for using preg_replace-placeholders "$1" in PHP context:
# ↓ ⇓ ↓
preg_replace("/#(\w+)/e", strtopupper($1) )
Where the callback should have been quoted. (Now the /e regex flag has been deprecated. But it's sometimes still misused in preg_replace_callback functions.)
The same identifier constraint applies to object properties, btw.
↓
$json->0->value
While the tokenizer/parser does not allow a literal $1 as variable name, one could use ${1} or ${"1"}. Which is a syntactic workaround for non-standard identifiers. (It's best to think of it as a local scope lookup. But generally: prefer plain arrays for such cases!)
Amusingly, but very much not recommended, PHPs parser allows Unicode-identifiers; such that $➊ would be valid. (Unlike a literal 1).
Stray array entry
An unexpected long can also occur for array declarations - when missing , commas:
# ↓ ↓
$xy = array(1 2 3);
Or likewise function calls and declarations, and other constructs:
func(1, 2 3);
function xy($z 2);
for ($i=2 3<$z)
So usually there's one of ; or , missing for separating lists or expressions.
Misquoted HTML
And again, misquoted strings are a frequent source of stray numbers:
# ↓ ↓
echo "<td colspan="3">something bad</td>";
Such cases should be treated more or less like Unexpected T_STRING errors.
Other identifiers
Neither functions, classes, nor namespaces can be named beginning with a number either:
↓
function 123shop() {
Pretty much the same as for variable names.
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,
];