1

Consider the following two files:

ParentClass.php

<?php

abstract class ParentClass
{
    abstract public function foo(array $arg1, array $arg2);
}

ChildClass.php

<?php

require_once "ParentClass.php";

class ChildClass extends ParentClass
{
    public function foo(array $arg1)
    {
        print_r($arg1);
    }
}

Now, let's try linting these files:

$ php -l ParentClass.php 
No syntax errors detected in ParentClass.php

$ php -l ChildClass.php
No syntax errors detected in ChildClass.php

Great, no syntax errors!

But wait! There's a problem:

$ php ChildClass.php 
PHP Fatal error:  Declaration of ChildClass::foo(array $arg1) must be compatible 
with ParentClass::foo(array $arg1, array $arg2) in 
/home/mkasberg/php_syntax_check/ChildClass.php on line 5

So, why didn't php -l catch it? That's an error that could be caught at "compile time" (although php is not a compiled language). Seems like php -l could notice that the declarations are not compatible. Is there a way to run php -l such that it will catch this error? Is there another tool that will catch the error?

mkasberg
  • 16,022
  • 3
  • 42
  • 46

1 Answers1

1

The lint operation does a syntax check only. It doesn't run the code so the parser doesn't know anything about ParentClass.

However if you put both of the class definitions into a single file then the errors will show up:

$ php -l test.php

Fatal error: Declaration of ChildClass::foo() must be compatible with ParentClass::foo(array $arg1, array $arg2) in test.php on line ..

Errors parsing test.php

From PHP docs - Command line options:

-l --syntax-check
Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in is written to standard output and the shell return code is 0. On failure, the text Errors parsing in addition to the internal parser error message is written to standard output and the shell return code is set to -1.

This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.

(Note that the -f option actually runs the script.)

Shira
  • 6,392
  • 2
  • 25
  • 27
  • Good observation that it will catch errors in the same file. Unfortunately, that doesn't scale well. This example is a bit contrived - I'm really interested in doing this for much larger projects. – mkasberg Jun 21 '16 at 23:25
  • 1
    Yes, that was just to demonstrate how `php -l` operates. See http://stackoverflow.com/questions/378959/is-there-a-static-code-analyzer-like-lint-for-php-files – Shira Jun 22 '16 at 00:43
  • Phan looks interesting. Perhaps I'll start using that after we upgrade to PHP 7. – mkasberg Jun 23 '16 at 15:17