Is it somehow possible to identify unused variables in a PHP file in Emacs?
With other languages, this is possible by using tools such as flymake. I've already enabled Flymake to show syntax errors for my PHP files on the fly, but still it's frustrating that PHP logic errors are sometimes due to situations like:
<?php
$foo = whatever();
$bar = something($fo);
...
Note the typo on $foo
that will contribute to the developer's headache and to his exorbitant use of coffee.
UPDATE:
After the hints by Pascal and Gabor, I set in my php.ini:
error_reporting = E_ALL | E_STRICT
When I run php from command line, I'm now able to see the notice about the undefined variable (with or without the -l option):
> php -r '$foo = 3; echo $fo;'
PHP Notice: Undefined variable: fo in Command line code on line 1
> php -r '$foo = 3; echo $fo;' -l
PHP Notice: Undefined variable: fo in Command line code on line 1
This is what I'm currently using in my .emacs. It works perfectly fine with parse errors, but I'm still not able to match on the notices, though :(
;; FlyMake for Php (require 'flymake)
(defun flymake-php-init ()
"Use php to check the syntax of the current file."
(let* ((temp (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace))
(local (file-relative-name temp (file-name-directory buffer-file-name))))
(list "php" (list "-f" local "-l"))))
(add-to-list 'flymake-err-line-patterns
'("\\(Parse\\|Fatal\\) error: +\\(.*?\\) in \\(.*?\\) on line \\([0-9]+\\)$" 3 4 nil 2))
(add-to-list 'flymake-err-line-patterns
'("Notice: \\(.*\\) in \\(.*\\) on line \\([0-9]+\\)" 2 3 nil 1))
(add-to-list 'flymake-allowed-file-name-masks '("\\.php$" flymake-php-init))
I've also tried Gabor's configuration. Same result. Fine with errors, bad with notices.
Please note that from command line, parse errors look like:
> php -r '$fo o = 3; echo $fo;' -l
PHP Parse error: syntax error, unexpected T_STRING in Command line code on line 1
I don't get why Notices are not matched. I've tried the regular expression separately and it seems to match correctly:
(search-forward-regexp "Notice: \\(.*\\) in \\(.*\\) on line \\([0-9]+\\)")
PHP Notice: Undefined variable: fo in Command line code on line 1
(C-x C-e
will jump to the end of the lines).
Finally, I disabled XDebug for now, since the notices were originally reported as:
PHP Notice: Undefined variable: fo in Command line code on line 1
PHP Stack trace:
PHP 1. {main}() Command line code:0
So, I guess I should slightly change the regexp to match the multiline errors. Any hint about this?