Validate PHP code from Sublime Text 2

December 6th, 2013

If there's an error in your php code you might not always get an output of the error.

Since php can't be be compiled, we don't get the code validated at runtime. Instead we can run php with the -l flag:

$ php -l myfile.php

This will hopefully say No syntax errors detected in myfile.php. But if there is an error, you will get something like this:

PHP Parse error:  syntax error, unexpected '=' in myfile.php on line 2
Errors parsing build_db.php

Sublime Text 2

The text editor Sublime Text 2 is pretty awesome. It works on multiple platforms and you create your own commands amongst other things.

You can for example set a build system by going to Tools -> Build System -> New Build System.... This will open a new tab in the editor, where you can past the following.

{
  "cmd": ["/usr/bin/php", "-l", "$file"],
  "selector": "source.php",
  "file_regex": "^Parse error: .* in (.*?) on line ([0-9]*)"
}

Save the file as something like php-validator.sublime-build. The editor should open the save prompt at the correct path. For me (on Ubuntu) it was ~/.config/sublime-text-2/Packages/User/.

Now you can validate your php files from the editor by selecting php-validator (or whatever you called it) in Tools -> Build System (once) and then click Ctrl + B (or the equivalent command on your system.

Source: Joey Baker

Categories

IT

Tags