PHP怎么排插语法错误,PHP解析/语法错误和如何解决他们?

Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers it's just part of the learning process. However, it's often easy to interpret error messages such as:

PHP Parse error: syntax error, unexpected '{' in index.php on line 20

The unexpected symbol isn't always the real culprit. But the line number gives a rough idea where to start looking.

Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.

While not every case matches the other. Yet there are some general steps to solve syntax mistakes.

This references summarized the common pitfalls:

Closely related references:

And:

While Stackoverflow is also welcoming rookie coders, it's mostly targetted at professional programming questions.

Answering everyones coding mistakes and narrow typos is considered mostly off-topic.

So please take the time to follow the basic steps, before posting syntax fixing requests.

If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.

If your browser displays error messages such as "SyntaxError: illegal character", then it's not actually php-related, but a javascript-syntax error.

解决方案

What are syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can't guess your coding intentions.

d0b3ad5fe33e82eb1f6957138e9db304.gif

Most important tips

There are a few basic precautions you can always take:

Use proper code indentation, or adopt any lofty coding style.

Readability prevents irregularities.

Use an IDE or editor for PHP with syntax highlighting.

Which also help with parens/bracket balancing.

cead69aa1a1359ea9861602bedd2d269.png

Read the language reference and examples in the manual.

Twice, to become somewhat proficient.

How to interpret parser errors?

A typical syntax error message reads:

Parse error: syntax error, unexpected T_STRING, expecting ';' in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as T_STRING explains which symbol the parser/tokenizer couldn't process finally. This isn't necessarily the cause of the syntax mistake however.

It's important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

Open the mentioned source file. Look at the mentioned code line.

For runaway strings and misplaced operators this is usually where you find the culprit.

Read the line left to right and imagine what each symbol does.

More regularily you need to look at preceding lines as well.

In particular missing ; semicolons are missing at the previous line end / statement. (At least from the stylistic viewpoint. )

If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indendation to simplify that.

Look at the syntax colorization !

Strings and variables and constants should all have different colors.

Operators +-*/. should be be tinted distinct as well. Else they might be in the wrong context.

If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker.

Having two same-colored punctuation characters next to each other can also mean trouble. Usually operators are lone, if it's not ++ or -- or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.

Whitespace is your friend.

Follow any coding style.

Break up long lines temporarily.

You can freely add newlines between operators or constants and strings. The parser will then concretise the line number for parsing errors. Instead of looking at very lengthy code, you can isolate the missing or misplaced syntax symbol.

Split up complex if statements into distinct or nested if conditions.

Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = less errors.)

Add newlines between:

Code you can easily identify as correct,

The parts you're unsure about,

And the lines which the parser complains about.

Partitioning up long code blocks really helps locating the origin of syntax errors.

Comment out offending code.

If you can't isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

When you can't resolve the syntax issue, try to rewrite the commented out sections from scratch.

As newcomer avoid some of the confusing syntax constructs.

The ternary ? : condition operator can compact code and is useful indeed. But it doesn't aid readability in all cases. Prefer plain if statements while unversed.

PHPs alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

The most prevalent newcomer mistakes are:

Missing semicolons ; for terminating statements / lines.

Mismatched string quotes for " or ' and unescaped quotes within.

Forgotten operators, in particular for string . concatenation.

Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?

Don't forget that solving one syntax problem can uncover the next.

If you make one issue go away, but another crops up in some code below, you're mostly on the right path.

If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

Restore a backup of previously working code, if you can't fix it.

Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.

Invisible stray unicode characters: In some cases you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.

Try grep --color -P -n "[\x80-\xFF]" file.php as first measure to find non-ASCII symbols.

In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularily can find their way into source code.

Take care of which type of linebreaks are saved in files. PHP just honors \n newlines, not \r carriage returns. Which is occasionally an issue for MacOS users (even on OS X for misconfigured editors).

Check your PHP version. Not all syntax constructs are available on every server.

Don't use PHPs reserved keywords as identifiers for functions / methods, classes or constants.

Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren't as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

Further guides:

White screen of death

If your website is just blank, then typically a syntax error is the cause.

Enable their display with:

error_reporting = E_ALL

display_errors = 1

In your php.ini generally,

or via .htaccess for mod_php,

or even .user.ini with FastCGI setups.

Enabling it within the broken script is too late, because PHP can't even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php:

error_reporting(E_ALL);

ini_set("display_errors", 1);

include("./broken-script.php");

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHPs error_log and look into your webservers error.log when a script crashes with HTTP 500 responses.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值