When you program in PHP, or in any language, there will be times when you receive confusing error messages. Often, an error message does not actually indicate the cause of a problem directly, but rather the knock-on effects. In PHP, the "unexpected t_string" error normally means that PHP execution has encountered a problem processing the line after the one with the syntax error on it. Fixing the error is not typically difficult, as the message usually contains information leading you to the source.
PHP Parse Errors
The PHP interpreter is responsible for processing the syntax you write in PHP code. Depending on your server's PHP setup, you should be able to see details of any syntax errors in your PHP code when it executes. This normally happens when you browse to a page which is attempting to use the code with the error in it. PHP parse error messages tend to be quite informative, even if they look confusing to you at first. In most cases, you will receive an indication of where the error has been detected in terms of line numbers. However, it is often the case that the syntax mistake actually occurs on a line preceding the line indicated.
The cause of the "unexpected t_string" error is often a missing semi-colon. All statements in PHP end with a semi-colon, as in the following example syntax excerpt:
$name = "Mary";
If the semi-colon is missing, the PHP interpreter will not be able to process this line or the line following it correctly. In such cases, the PHP error message displayed in the browser may include the "unexpected t_string" phrase. The interpreter is indicating that characters processed were "unexpected" because the characters following the initial code statement do not conform to a normal structure. This is why it is often the line after the one with the problem on it that appears in the message.
The solution to the "unexpected t_string" error is to correct the syntax on the line causing it. The most difficult part of debugging is often finding the source of an error rather than fixing it. This is why any line numbers indicated in an error message are useful, although they often point you to a place later in the code than the actual syntax error. If you receive this error, it's therefore advisable to check the line before the line number indicated in the error message, adding any missing elements such as ending semicolons.
As with all programming errors, taking a preventive approach minimizes the amount of debugging necessary. Rather than fixing errors when you discover them at runtime, when your PHP pages are accessed, preventing them from occurring in the first place is preferable. Using an Integrated Development Environment to write your PHP code increases the chances of discovering errors while you're developing. IDEs for PHP include Dreamweaver, NetBeans and Eclipse.
- Photo Credit Goodshoot/Goodshoot/Getty Images