Experiment with Basic PHP Syntax Errors
When you start PHP, you will see errors. They stop your program, and sometimes a small mistake takes a long time to find. A good way to get friendly with them is to make the mistakes yourself and see the message. Then you will know them when they come in real work.
A working program
<?php
echo "Hello World!";
?>
Output:
Hello World!
Now we will break this program in different ways. Run each example on your local computer and read the message. The file name and line number in your messages will be different.
Experiment 1: missing semicolon
<?php
echo "Hello"
echo " World";
?>
Parse error: syntax error, unexpected token “echo”, expecting “,” or “;” in /path/index.php on line 3
PHP reports the line after the missing semicolon, because it only understands the problem when it reads the next statement.
Experiment 2: undefined variable
<?php
$name = "Robin";
echo $nme; // typing mistake
?>
Warning: Undefined variable $nme in /path/index.php on line 3
This is only a warning, so the script goes on. The cause is a typing mistake, or the different case of the variable name.
Experiment 3: unknown function
<?php
printt("Hello");
?>
Fatal error: Uncaught Error: Call to undefined function printt()
Experiment 4: bracket not closed
<?php
if (true) {
echo "Yes";
?>
Parse error: Unclosed ‘{‘ on line 2
Experiment 5: divide by zero
<?php
echo 10 / 0;
?>
Fatal error: Uncaught DivisionByZeroError: Division by zero
What to learn from it
- Parse errors are syntax mistakes. The program does not start at all.
- Warnings and notices do not stop the program, but they show a problem to fix.
- Fatal errors stop the program in the middle.
See all types of errors in PHP Errors and the types of errors in PHP.
| Tutorials |
|---|
| PHP Introduction |
| PHP Terminology |
| PHP Installation |
| PHP Syntax |
| PHP Comments |
| PHP exit() Function |
| Exercises & Assignments |
|---|
| Write a program to print “Hello World” using echo |
| Simple Tips for PHP Beginners |
| Experiment with Basic PHP Syntax Errors |
| Using phpinfo() – Display PHP Configuration & Modules |