Search code examples
phpphpstan

What is the type of the handle given back by fopen()?


I have this code:

class CsvWriter
{
    private $handle;


    public function openToFile($filePath): void
    {
        $this->handle = fopen($filePath, 'wb+');
        if (false === $this->handle) {
            throw new FileException('Could not open file ' . $filePath, 8788);
        }
    }
}

PHPStan complains that

Property App\Domain\Csv\CsvWriter::$handle has no type specified.

Well that is true, but what type is it?

private resource $handle;

does not work.

What is the correct property of my $handle?


Solution

  • Not everything can be expressed as first-class type annotation. In those cases, a docblock comment can be used instead:

    /** @var resource|false */
    private $handle = false;