Skip to content

unsafe-new-static

PHPsuspiciousno fixdefault: offphp/phpstan

Reports new static in a class that is not final and has no final or abstract constructor of its own. A constructor or a final parent in another file cannot be seen; the @phpstan-consistent-constructor tag of the class itself is.

new static builds the class of the caller, so a subclass can be built with its own constructor with other parameters, and the call in the parent fails with a missing argument.

To fix, make the class or the constructor final, or call new self.

Reported
<?php
class A { function make() { return new static(); } }
final class B { function make() { return new static(); } }
class C { final public function __construct() {} function make() { return new static(); } }
trait T { function make() { return new static; } }
class D { function make() { return new self(); } }
/** @phpstan-consistent-constructor */
class E { function make() { return new static(); } }
php:
lint:
rules:
unsafe-new-static: warn # off (default), warn, error

Enabled by the presets: php/phpstan.

Suppress one line with sudsy-disable-next-line unsafe-new-static in a comment of the file’s language.

The same check in other tools. full: Sudsy reports what the upstream rule reports; partial: only part of it, as the last column says.

Tool Rule Match What differs
phpstan new.static partial A class without a final class or final or abstract constructor of its own; a constructor or final parent in another file, and a @phpstan-ignore comment, cannot be seen (about 17 findings of the 317).