Psalm: Add stringable type

Created on 31 Jul 2019  路  6Comments  路  Source: vimeo/psalm

I think a stringable type would be beneficial to psalm. It would represent any type that can be cast to a string, such as any scalar type, or an object with a __toString method defined.

The following PHP snippet may be useful:

function can_be_string($v): bool
{
    return $v === null || is_scalar($v) || method_exists($v, '__toString');
}

Most helpful comment

@muglug what should be the type of $a for this to be a valid cast?

$b = (string) $a;

All 6 comments

I don't see much value in this (unless PHP adds it too).

Here's what I see in it:

In a translation system, I want to be able to pass an array that looks like array<stringable, stringable> for replacements, e.g.

[
   'foo' => 'bar',
   1 => 2,
   'baz' => new StringableObject,
]

Instead I have to do something like array<int|string, scalar> but that doesn't cover stringable objects

You could define a Stringable interface with just a single __toString method, then require the array type to be array<string|Stringable>

For library code that isn't very useful, if I want users to be able to pass any stringable object

@muglug what should be the type of $a for this to be a valid cast?

$b = (string) $a;

This was effectively fixed in d532133325bd37 or about, as far as I understood.

Was this page helpful?
0 / 5 - 0 ratings