> On 21 Oct 2014, at 00:27, Lars Strojny <l...@strojny.net> wrote:
> 
> I like the proposal except for one thing: the functions returning false in 
> case of an error. As the next logical function would be "to_bool()", I 
> foresee a lot of trouble with regards to API design as returning false there 
> either means successful cast to false or an error while casting. What about 
> changing the functions to take an $isError variable as a second argument?
> 
> $value = to_string(1.2, $isError);
> if ($isError) {
>   ...
> }
> 
> Alternatively one could do the same thing with an $isSuccess variable:
> 
> $value = to_string(1.2, $isSuccess);
> if (!$isSuccess) {
>   ...
> }
> 
> Thoughts?

This is an interesting question. It’s actually one I’d considered myself, I 
think I briefly mention it in the RFC. However, I don’t expect it to be a 
problem, and the reason is really quite simple: There’s no clear-cut 
one-size-fits all boolean casting function you could make, and booleans are 
trivial to validate yourself.

Adding something like is_bool() would be possible, the problem is what 
behaviour it would have, and there are too many possibilities. Do you accept 1 
and 0? If so, do you accept all non-zero values, or not? Is “true” TRUE or is 
it FALSE? Is “yes” TRUE or is it FALSE? Do “true” and “yes” validate? Do they 
not? Does the empty string validate? Does it not? Bear in mind that boolean 
casting was one of the most problematic areas of the abandoned Scalar Type 
Hinting RFC: there’s no clear set of definitely boolean values, nor a clear 
idea of which mean which boolean value. Basically, I don’t think we’d ever be 
able to draw the line.

The other thing is, well, there’s not really a need. You can quite simply do 
something like this: if ($value !== “true” && $value === “false”) { /* error! 
*/ } - and while this is less convenient than is_bool, as I mentioned before, 
there’s no real agreement on what is_bool should do so you’d have to do this 
anyway. A thought: A weird, but workable solution for one particular style is 
[“true” => TRUE, “false” => FALSE][$value] ?? NULL - whether that’s a wonderful 
or horrible use of PHP is up to you. ;)

So I don’t think using FALSE here is a problem, since I doubt is_bool would 
ever be added.

Regarding using a reference variable for the output, I don’t like that idea 
much. It doesn’t chain very well… and would it fail a strict type hint, if we 
added that? Even if it somehow did, I don’t think it is a good idea. Since I 
don’t think is_bool will happen, there’s also no real need, either.
--
Andrea Faulds
http://ajf.me/





--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to