Blog

Blog

All Articles(https://phpstan.org/blog)

Releases(https://phpstan.org/blog/releases)

Guides(https://phpstan.org/blog/guides)

Other(https://phpstan.org/blog/other)

Other Sections

RSS(https://phpstan.org/rss.xml)

Sponsor PHPStan!(https://phpstan.org/sponsor)

Solving PHPStan error “Unsafe usage of new static()”

January 13, 2021 · 4 min read

This error is reported for new static() calls that might break once the class is extended, and the constructor is overridden with different parameters.

Consider this example:

<?php declare ( strict_types = 1 ) ;

class Foo {

public function __construct ( int $i ) { }

public function doFoo ( ) : void { new static ( 1 ) ; // PHPStan reports: Unsafe usage of new static() }

}

class Bar extends Foo {

public function __construct ( string $s ) { }

}

( new Foo ( 1 ) ) -> doFoo ( ) ; // works, returns Foo ( new Bar ( 's' ) ) -> doFoo ( ) ; // crashes with: Argument #1 ($s) must be of type string, int given

So the PHPStan rule protects you from accidentally breaking your code when extending the class and defining a different constructor.

Let’s go over possible solutions:

Make the class final #

This is the easiest course of action - you might realize you actually don’t want the class to be extended and it’s been open for inheritance by mistake. Once you make the class final, the error is no longer reported. At that point you can also change new static() and make it just new self() without changing the functionality.

final class Foo { ... }

Make the constructor final #

If you want the class open for extension, you can disallow overriding the constructor in child classes and make the code safe that way.