Re: [Discussion] is_string(), string type and objects implementing __toString()

From: Date: Wed, 08 Mar 2017 15:14:05 +0000
Subject: Re: [Discussion] is_string(), string type and objects implementing __toString()
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-98428@lists.php.net to get a copy of this message
Hi Rowan, On Wed, Mar 8, 2017 at 4:29 PM, Rowan Collins <rowan.collins@gmail.com> wrote: > Hi Andrey, > > I think this is an interesting area to explore, but do think the scope needs to be widened > slightly. > > > On 8 March 2017 12:25:54 GMT+00:00, Andrey Andreev <narf@devilix.net> wrote: >>I ultimately wouldn't care if it's a separate function and did in fact >>think of an is_stringable() function, but wasn't happy with the naming >>- who's to say that e.g. integers aren't stringable? Bar >>horribly-verbose names like >>"string_or_objects_implementing__toString", I don't think there's a >>way to avoid that ambiguity. :/ >>If we want a "stringable" type though > > Sometimes, the fact that you can't think of a good name for a function is a clue that the > function isn't solving a well-defined problem. > > In this case, why *wouldn't* the function return true for integers? If the question the > function is asking is "can this value be cast to string?" then the answer for any integer > should be "yes". If the question is "will it pass a strict type check as a > string", then the answer for objects would always be "no". Am I missing a situation > where casting an object would be safe, but casting an integer wouldn't? > Well, it may be confusing and/or a bit inconsistent since what __toString() does is casting (and the idea will probably be ridiculed because of this), but putting that aside - it's not about casting at all. The question is rather "is this value a string?", only with the added assumption that __toString() objects are treated as "string objects" and thus fulfill the condition (another reason why I went for an is_string() parameter). It's not so much about whether casting would result in loss of data, which is what I assume you mean by "safe", but about whether the value was ever intended to be used as a string - an object implementing __toString() obviously is, while the same cannot be certainly said for integers. An integer can be a bit flag, or a key from an id => name pair, etc. Cheers, Andrey.

« previous php.internals (#98428) next »