Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

No Returntype But Still, Only String

By Frederic Bouchery

<?php

declare(strict_types=1);

class x {
    function __toString() {
        return 1;
    }
}

echo new x;

Without a return type (or mixed), a method may return any type of data. This is not the case for the magic method __toString, as it really should return a string. So, even without a return type, it complains about the type.

That trick requires strict_types though.

See Also

PHP Features

Last updated: 10 September 2026