[php-src] Issue #12097: Stringable object should accepted as type-hinted string when in strict-typing mode
| From: | lkankowski | Date: | Thu, 31 Aug 2023 21:07:52 +0000 |
| Subject: | [php-src] Issue #12097: Stringable object should accepted as type-hinted string when in strict-typing mode | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-245305@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/12097
Author: lkankowski
### Description
When function/method parameter is type-hinted as
string it should also accept any
Stringable object.
It would be especially useful, when string parameter is nullable, so we can just pass an object
instead doing something like: null === $nullableVar ? null : (string) $nullableVar.
https://3v4l.org/OBatI#v8.2.10
Sample code:
```php
<?php
declare(strict_types=1);
final class SomeStringable {
public function __toString(): string {
echo "__toString executed" . PHP_EOL;
return "foo";
}
}
final class SomeClass {
public function __construct(public ?string $value)
{}
}
$nullableVar = new SomeStringable(1);
//$nullableVar = null;
//$result = new SomeClass(null === $nullableVar ? null : (string) $nullableVar); // works
$result = new SomeClass($nullableVar); // Fatal error
var_dump($result->value);
```
Resulted in this output:
```
Fatal error: Uncaught TypeError: SomeClass::__construct(): Argument #1 ($value) must be of type
?string, SomeStringable given, called in /in/248kv on line 21 and defined in /in/248kv:14
Stack trace:
#0 /in/248kv(21): SomeClass->__construct(Object(SomeStringable))
#1 {main}
thrown in /in/248kv on line 14
Process exited with code 255.
```
But I expected this output instead:
```
__toString executed
string(3) "foo"
```
### PHP Version
8.2.10
### Operating System
_No response_