Reputation:
Is there a way to validate my PHP code for syntax errors using PHP itself?
Upvotes: 8
Views: 3106
Reputation: 11206
Building on what others have said:
error_reporting(E_ALL);
Simply using PHP's own error messages is good enough. However, if you really want to get anal and use a set "standard" you can opt for a PHP Code Sniffer, which for example you can implement as pre-commit hooks to your version control system.
Here's a SO question which explains their usefulness: How useful is PHP CodeSniffer? Code Standards Enforcement in General?
Upvotes: 2
Reputation: 400972
You can validate the syntax without running a PHP script itself, using php
from the command line, with the option "-l
" :
$ php --help
Usage: php [options] [-f] <file> [--] [args...]
php [options] -r <code> [--] [args...]
php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
php [options] -- [args...]
php [options] -a
...
-l Syntax check only (lint)
...
For example, with a file that contains :
<?php
,
die;
?>
(Note the obvious error)
You'll get :
$ php -l temp.php
PHP Parse error: syntax error, unexpected ',' in temp.php on line 3
Parse error: syntax error, unexpected ',' in temp.php on line 3
Errors parsing temp.php
Integrating this in a build process, or as a pre-commit SVN hook, is nice, btw : it helps avoiding having syntax errors in production ^^
Upvotes: 17
Reputation: 31828
You can run php with the -l
or --syntax-check
flag. It checks the syntax of the supplied file without actually running it
php --syntax-check myfile.php
Upvotes: 11
Reputation: 94645
PHP engine itself.
To turn on error messages:
error_reporting(E_ALL);
Upvotes: 2