Question

Is there a way to avoid the parent:: static accessor in PHP classes, or is this one of those times to use @SuppressWarnings(StaticAccess)?

On the same lines, it seems like this StaticAccess warning is popping in suspicious places. Exception handling, for instance - when I throw new Exception(...), PHPMD complains about static access. But...there's not really another way to do it (that I've found) so I've got more warnings suppressors than I'd like. Is this normal?

EDIT

As requested, here's an example - it's pretty straightforward:

class aaa {
    private $someReasonForAnException = true;

    public function __construct() {
        echo 'AAA<br>';
        if ($this->someReasonForAnException) {
            throw new Exception("Something happened that's worth noticing!");
        }
    }
}

class bbb extends aaa {    
    public function __construct() {
        echo 'BBB<br>';
        parent::__construct();
    }
}

$BBB = new bbb();

PHPMD will report two errors with the above: a StaticAccess error on the Exception, and a StaticAccess error on the parent::__construct() call.

To avoid that, I've got to notate both classes with @SuppressWarnings , which seems clunky, and also won't show "real" static access problems.

Was it helpful?

Solution 2

There is no other way to reference parent's method implementation on PHP. There is nothing wrong with your code, PHPMD is drunk. The only problem you'd have with static access is because PHP allows you to call an instance method as a static method if it does not reference $this variable, but there is no point on doing so. You can ignore this kind of warning.

Edit:

If you have something like this:

class Foo {
    public function bar() {
        echo 'bar';
    }
}

PHP will allow you to do:

Foo::bar(); // works

But if you have this:

class Foo {
    private $bar = 'bar';
    public function bar() {
        echo $this->bar;
    }
}

Foo::bar(); // fatal error

OTHER TIPS

A simple and sustainable solution might be to

Because I use a lot of self:: for constants, change phpmd code to accept self:: and parent::.

In the program PHP/PMD/Rule/CleanCode/StaticAccess.php at line 36, change to:

if ($this->isReferenceInParameter($reference)
    || $reference->getImage() === 'self' 
    || $reference->getImage() === 'parent' 
    ) {
    continue;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top