Post #3738697
2026-07-11 11:46 UTC
#PHP I've notice that I barely use __toString nowadays. I came to realise that there is no one true single string representation for anything. So __toString is a bad micro/early optimisation that should be avoided. It is conceptually a bad idea. I prefer toWhateverRepresentationString. it might be a bit longer to type but it won't bite you in six months.
PS: I have the share the same thoughts for toArray.
Replies (1)
-
@heiglandreas@phpc.social 2026-07-11 11:49
@nyamsprod@phpc.social For a ValueObject IMO __toString makes (can make) sense. If that is not the case, then the question is whether the object itself should decide upon which kind of string it should represent to. That's IMO too much context to be known by an object. Same for `toArray` - too much context to be known. Serializing an object is not the objects task.