Making Sense Of PHP Errors - The Way of The Interpreter
(Page 2 of 4 )
To find out why the interpreter reports an error on a certain line, first one must learn how the interpreter parses PHP code. I wont go into detail in this article, however I will discuss the simple concepts that cause errors more often than not.
Variable Declaration When declaring a variable in a statement such as:
$variable = 'value'; The interpreter first evaluates the right hand side of the statement (all code to the right of the equals sign) first. In programming books this is referred to the RHS (right hand side) of the statement. It is this part of the statement that often causes errors. If improper syntax is used, a parse error occurs.
Parse Errors Parse error: parse error, unexpected T_WHILE in c:\program files\apache group\apache\htdocs\script.php on line 19 Ugh. Parse errors, one after another, keep on showing up every time you fix the previous error. Since PHP stops executing the script after the first parse error, they are especially annoying to debug.
Additionally, parse errors are horribly un-informative, rarely ever reporting the line number where the error was picked up. The reason for this is that when you make a mistake, it might seem like valid syntax to the interpreter for several lines until it encounters invalid syntax, most likely a reserved word used in an expression, such as:
while = 10; // Bad –- while is a reserved word and can't be assigned a value Reserved words are words like for, while, function, and if that PHP uses to evaluate your code. You can not name variables after these reserved words and if you do then PHP will spit more errors than you can chew.
An example might be helpful at this point. Take a look at the PHP code shown below:
<?php
$b = "somevalue"
if($b == "somevalue"){
print "Hello world!";
}
?> The mistake is on the "$b =" line (no semicolon ending the statement), so the error should be "parse error: expected ; on line 3", right? Not according to the interpreter.
Parse error: parse error, unexpected T_IF in c:\program files\apache group\apache\htdocs\ereg2.php on line 4 On line 4, the if() syntax is perfect. So what is the interpreter getting confused from? The clue is the "unexpected T_IF" part. When an "unexpected T_???" error occurs, it means that the interpreter encountered its respective reserved word where it shouldn't be. T_IF for if(), T_WHILE for while(), T_FOR for for(), etc.
Luckily, there are a few easy causes for these errors:
- The statement wasn't ended with a semicolon (;), like in the example above.
- A quote was not properly escaped (' instead of \' or " instead of \") in a string.
Next: Other Common Errors >>
More PHP Articles
More By Elan Bechor