opened
hkdobrev
username_0
When a class has a `__toString()` method, an instance of it should be able to be passed to a method expecting a string.

Please let me know if this sounds right.

I currently get an error like that with level 5:

```
Parameter #1 $expression of method Foo::parse() expects string, Expression given.
```
Where
```php
class Expression
{
    public function __toString()
    {
        // ...
    }
}
```
Accept classes with __toString() method as valid string arguments
issue
created
ondrejmirtes
username_1
You're right, this can be correctly handled how you suggested. It hasn't been until now because I consider using `__toString` to be a not very good programming practice. It's very limiting - what if an object has two or more possible string representations? Like "First name Last name" or "Last Name, First name"? Also, `__toString` cannot throw exception. The only acceptable `__toString` usage is for debugging purposes. So your entities could probably implement something like this:

```
public function __toString()
{
    return get_class($this) . '#' . $this->getId();
}
```

Passing an object where only string is accepted is often a mistake rather than an intent. But I agree that this should be allowed by default with a possible stricter setting to reject it.
comment
created
hkdobrev
username_0
@username_1 I agree with all of your remarks, but when you are trying to use PHPStan to detect problems in a legacy system which has a ton of classes already using `__toString()`, this should be covered. Also when you are dealing with 3rd party libraries which use such patterns, it's only sensible to detect this by default.

Also some people coming from different languages may say this is their preferred practice of writing classes. Even if it's not OOP. The same logic applies in part for `Countable`, `ArrayAccess`, `Iterable` and `Traversable` but with them we at least have interfaces and a more documented and a sensible way of doing things.
comment
created
ondrejmirtes
username_1
I agree. PHPStan cannot be opinionated since it's for finding bugs, so it
will accept objects with __toString in places where string belongs by
default :)
comment
created
ondrejmirtes
username_1
Fixed with https://github.com/phpstan/phpstan/commit/254def88b153eb9dfa8ceab4a92eed92ccab8ca2.
comment
closed
ondrejmirtes
username_1
issue