Is there a way to validate my PHP code for syntax errors using PHP itself?
-
6To validate what? PHP’s syntax? You will get a parsing error if the syntax is invalid.Gumbo– Gumbo2009-09-20 14:01:25 +00:00Commented Sep 20, 2009 at 14:01
-
I think he's on the lookout for something like "lint for PHP". That question has been asked here before: see stackoverflow.com/questions/378959/… in particular, PHPlint (icosaedro.it/phplint) looks promising.bart– bart2010-04-10 16:55:32 +00:00Commented Apr 10, 2010 at 16:55
4 Answers
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 ^^
Comments
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?