1.2.271. Could Be Stringable

Stringable is an interface that marks classes with a custom method to cast the object as a string. It was introduced in PHP 8.0.

Classes that defined a __toString() magic method may be turned into a string when the typehint, argument, return or property, requires it. This is not the case when strict_types is activated. Yet, until PHP 8.0, there was nothing to identify a class as such.

<?php

// This class may implement Stringable
class x {
    function __tostring() {
        return 'asd';
    }
}

echo (new x);

?>

See also PHP RFC: Add Stringable interface and The Stringable interface.

1.2.271.1. Suggestions

  • Add implements stringable to the class definition

  • Add extends stringable to the interface definition

1.2.271.2. Specs

Short name

Classes/CouldBeStringable

Rulesets

All, Class Review, LintButWontExec, PHP recommendations

Exakat since

2.1.9

PHP Version

With PHP 8.0 and more recent

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

stringable, string, magic-method

Note

This issue may lint but will not run

Available in

Entreprise Edition, Exakat Cloud