Skip to content

Cannot use final methods inside a constructor #6613

Open
@simonwelsh

Description

@simonwelsh

The check for which methods can be called before a class has been fully initialised is limited to private methods. I feel like this should be extended to include final methods, as those also can't be overridden in child classes. This is especially true for methods that are final because the class is final.

For example, I would expect this file to report No errors:

<?hh // strict

class A {
    public string $foo;

    public function __construct() { $this->setFoo('Hello'); }

    final public function setFoo(string $foo): void { $this->foo = $foo; }
}

final class B {
    public string $foo;

    public function __construct() { $this->setFoo('Hello'); }

    public function setFoo(string $foo): void { $this->foo = $foo; }
}

Whereas, it gives these errors

File "/home/vagrant/foo.php", line 14, characters 18-28:
Class B does not initialize all of its members; foo is not always initialized.
Make sure you systematically set $this->foo when the method __construct is called.
Alternatively, you can define the member as optional (?...)
 (NastCheck[3015])

File "/home/vagrant/foo.php", line 14, characters 34-46:
Until the initialization of $this is over, you can only call private methods
The initialization is not over because $this->foo can still potentially be null (NastCheck[3004])

File "/home/vagrant/foo.php", line 6, characters 18-28:
Class A does not initialize all of its members; foo is not always initialized.
Make sure you systematically set $this->foo when the method __construct is called.
Alternatively, you can define the member as optional (?...)
 (NastCheck[3015])

File "/home/vagrant/foo.php", line 6, characters 34-46:
Until the initialization of $this is over, you can only call private methods
The initialization is not over because $this->foo can still potentially be null (NastCheck[3004])

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions