PHP errors for designers (the appendix)

One of the hardest things for me to learn is to read error messages and translate them into something meaningful that leads me to a solution.  I was excited to read Rachel Andrew’s “A Guide to PHP Error Messages for Designers,” but was a little surprised that some of the most basic ones were left out.  So here I’m going to present to you those most common of errors:

1. “Parse error: syntax error, unexpected ‘=’ in errors.php on line 1

Generally this means you used a single “=” to compare two values.  E.g. if(1=1){ echo “that”; }  In my head when I’m typing out a comparison I say “is equal to” in my head and the “to” reminds me to put down two equals signs.  Corny, I know.

2. Parse error: syntax error, unexpected $end in errors.php on line 1

This means you missed closing something before you closed your PHP tag “?>” E.g. <?php if(1==1){ echo “that”; ?>  In this case I need to close the if statement before I close php.

3. Notice: Use of undefined constant this – assumed ‘this’ in errors.php on line 1

My code: <?php if(this==’this’){ echo “this equals this”; } ?>  Here I forgot the “$” before my variable so PHP is letting me know it interpreted it as a string instead. You’ll actually get the output in this instance because PHP interprets the first value as a string and compares it against an identical string.  This can get confusing if–like me–you name variables after the values you expect them to hold.

4. Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in errors.php on line 1

Generally this means you’ve nested double/single quotes within the same string.  In this case, my code looks like: <?php echo “this is a “line” with “multiple” quotes”; ?>  To fix this, I can either escape the quotes with a backslash (\”) or change the first and last quotes to single quotes.  There is a difference between starting a string with a single or double quote, you can read all about that here.

Along that last line, my new favorite trick is the “heredoc” type string.  Often if we have a big chunk of HTML we need to output from PHP we’ll do several lines of something like:

$return = "<p>this is some HTML</p>";
$return .= "<p>my next line of html</p>";
$return .= "<p>another line with a $variable in it</p>"; 
echo $return;

Obviously you can accomplish the same thing from a single line, but when you start to mix in some variables it gets hard to read.  You could do the same thing much more simply with heredoc:

 

$return =<<<EOE
 
<p>this is some HTML</p>
<p>my next line of html</p>
<p>another line with a $variable in it</p>
 
EOE; 
echo $return;

 

There are some strict limitations about how to open and close a heredoc so take a good look at the documentation.

I hope this helps anyone struggling to get started with PHP!  If you run into an error you can’t explain feel free to post it in the comments.

Leave a Reply