PhpClean icon indicating copy to clipboard operation
PhpClean copied to clipboard

Spurious 'Deprecated __toString call' for function call from object

Open HenkPoley opened this issue 6 months ago • 0 comments

(string)$object->functionToCall() will be incorrectly be interpreted as ((string)$object) .., which is a deprecated cast since PHP 8.1.

<?php

declare(strict_types=1);

class BlaFoo
{
    public function __toString(): string
    {
        return 'BlaFoo';
    }
}

class Another {
    public function returnsBlaFoo(): BlaFoo {
        return new BlaFoo();
    }

    public function __toString(): string
    {
        return '';
    }
}

$another = new Another();

// No warning (correct)
(string)($another->returnsBlaFoo());

// Will warn: Deprecated __toString call, even though the Another object does not get cast
(string)$another->returnsBlaFoo();

// This is not the same as the next line, which should give this warning (and: method 'returnsBlaFoo' not found in string)
((string)$another)->returnsBlaFoo();

HenkPoley avatar Jul 08 '25 11:07 HenkPoley