# [RFC] Safe Casting Functions

- Thread: https://externals.io/message/78160
- Original archive: https://news-web.php.net/php.internals/78160
- Started by Andrea Faulds on 2014-10-20T22:57:48+00:00
- Messages: 72
- RFC: Safe Casting Functions (Declined) — https://externals.io/rfc/safe_cast.md
- Page 1 of 3: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/78160.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #78160 — Andrea Faulds — 2014-10-20T22:57:48+00:00

URL: https://externals.io/message/78160#78160

Good evening,

I am presenting a new RFC to add a set of three functions to do validated casts for scalar types:

https://wiki.php.net/rfc/safe_cast

Please read it.

Thanks!
--
Andrea Faulds
http://ajf.me/

---

## #78161 — Haralan Dobrev — 2014-10-20T23:16:24+00:00

URL: https://externals.io/message/78160#78161 · In reply to: #78160

In general I like this RFC.

I don't see why to_string would not accept and cast integers and floats to
strings. And even if there is a valid reason it is not mentioned.

If this gets accepted you should consider the naming in the user
documentation. Beginners should not consider these functions "safe" as in
"security", but only "safe" as in "no data loss".


> Good evening,
>
> I am presenting a new RFC to add a set of three functions to do validated
> casts for scalar types:
>
> https://wiki.php.net/rfc/safe_cast
>
> Please read it.
>
> Thanks!
> --
> Andrea Faulds
> http://ajf.me/

---

## #78162 — Andrea Faulds — 2014-10-20T23:18:41+00:00

URL: https://externals.io/message/78160#78162 · In reply to: #78161

> 
> 
> In general I like this RFC.
> 
> I don't see why to_string would not accept and cast integers and floats to strings. And even if there is a valid reason it is not mentioned.

It does accept and cast integers and floats to strings… I made an error in the Proposal section, my bad. If you look at the examples table and the tests in the patch, they are indeed accepted.

> If this gets accepted you should consider the naming in the user documentation. Beginners should not consider these functions "safe" as in "security", but only "safe" as in "no data loss”.

Right.

--
Andrea Faulds
http://ajf.me/

---

## #78163 — Lars Strojny — 2014-10-20T23:27:43+00:00

URL: https://externals.io/message/78160#78163 · In reply to: #78160

Hi Andrea,

> 
> 
> Good evening,
> 
> I am presenting a new RFC to add a set of three functions to do validated casts for scalar types:
> 
> https://wiki.php.net/rfc/safe_cast
> 
> Please read it.


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?

cu,
Lars

---

## #78164 — Andrea Faulds — 2014-10-20T23:39:25+00:00

URL: https://externals.io/message/78160#78164 · In reply to: #78163

> 
> 
> 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/

---

## #78165 — Stas Malyshev — 2014-10-21T00:32:46+00:00

URL: https://externals.io/message/78160#78165 · In reply to: #78160

Hi!

> I am presenting a new RFC to add a set of three functions to do validated casts for scalar types:
> 
> https://wiki.php.net/rfc/safe_cast
> 
> Please read it.

The main problem that happened with scalar typing RFC remains here:
third set of rules for casting types. Of course, since it's "just"
functions and not language constructs, we can have a set of functions
for any set of casting rules anybody wants. But I think it's still the
same problem here - having three sets of casting rules is not good.
Wait, we actually already have `FILTER_VALIDATE_INT` and
FILTER_VALIDATE_FLOAT, so that would be the fourth set of rules, and the
second set of validation rules, despite already having an extension
specially dedicated to filtering and validation. I think we should not
multiply entities needlessly - if we need some different validation
primitives, why not add them to filter, for example?
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #78166 — Andrea Faulds — 2014-10-21T00:49:07+00:00

URL: https://externals.io/message/78160#78166 · In reply to: #78165

Hi!

> 
> 
> The main problem that happened with scalar typing RFC remains here:
> third set of rules for casting types. Of course, since it's "just"
> functions and not language constructs, we can have a set of functions
> for any set of casting rules anybody wants. But I think it's still the
> same problem here - having three sets of casting rules is not good.

We have more than three sets of casting rules, but at least these ones are rather straightforward.

> Wait, we actually already have `FILTER_VALIDATE_INT` and
> FILTER_VALIDATE_FLOAT,

Actually, to_int is very close to FILTER_VALIDATE_INT, and I’m not sure, but I think to_float may be close to FILTER_VALIDATE_FLOAT. The main difference with integers is rejection of whitespace and toString-able objects.

> so that would be the fourth set of rules, and the
> second set of validation rules, despite already having an extension
> specially dedicated to filtering and validation. I think we should not
> multiply entities needlessly - if we need some different validation
> primitives, why not add them to filter, for example

The main point of the RFC is to add casting functions as an alternative to the built-in explicit casts. Currently, the easiest way to convert to an integer is (int), but this is quite dangerous as it performs no validation whatsoever and cannot fail. to_int() and the like are intended to be just as convenient as an explicit cast, so that doing the safer thing (failing on garbage input) is not any more difficult. The hope is that the lazy developer will use `is_int()` instead of (int) when they need to explicitly cast, and  avoid the problems of the latter.

--
Andrea Faulds
http://ajf.me/

---

## #78167 — Josh Watzman — 2014-10-21T01:07:13+00:00

URL: https://externals.io/message/78160#78167 · In reply to: #78160

> Good evening,
> 
> I am presenting a new RFC to add a set of three functions to do validated casts for scalar types:
> 
> https://wiki.php.net/rfc/safe_cast
> 
> Please read it.
> 
> Thanks!

I think this is pretty cool, but I'm really worried about some of its typing implications. In particular:

> The functions return `FALSE` on failure instead of `NULL` because:

Throwing an exception or even returning `NULL` seems so much better than returning "false" -- "false" is a boolean, not an error, and despite some historical cases of PHP using "false" as a poor person's error code, it really isn't. If you want error codes, use error codes, or use exceptions, but having two kinds of failure, null vs false, is really confusing.

Addressing your arguments one by one:

> 	• If strict type hinting were added, they would fail for a nullable typehint

Throwing an exception also addresses this, in a much cleaner way. If you're worried about strict typing, then returning "false" is even worse, since the return type of, for example, to_int is now "int | bool" as opposed to "nullable-int" or "int" (if you throw).

> 	• `FALSE` is a traditional error value in PHP

Since this is a new function, one that doesn't interoperate in any complicated way with the existing library or affect BC, this doesn't seem that important. IMO a language should have one failure/absense-of-value, in most cases "null", and having a weird second case seems, well, weird. If you have more interesting failure cases, just throw an exception, or return null if you want, don't continue propagating a weird second kind of null (that isn't actually null, it's a boolean false).

Also, that we *couldn't* introduce a meaningful to_bool function, even if we decided we wanted it, indicates to me that returning false is the wrong thing to do.

> 	• `NULL` is used to signify the absence of a value - but what we want to signify is an invalid value (similar to 0 vs NaN)

I might argue that failure is indeed absense-of-value, but an exception seems like a much better way to convey this.

It's also interesting to look at how other languages handle failures of this kind. Most imperative languages I know of either throw or return null; in particular, Python, which has fairly similar type system to PHP in a lot of ways, throws. Functional languages do more interesting things; Haskell does something complicated but morally equivalent to returning null. But I'm not aware of any language which specifically returns false.

---

## #78168 — Stas Malyshev — 2014-10-21T01:08:22+00:00

URL: https://externals.io/message/78160#78168 · In reply to: #78166

Hi!

> > […]
> 
> Actually, to_int is very close to FILTER_VALIDATE_INT, and I’m not
> sure, but I think to_float may be close to FILTER_VALIDATE_FLOAT. The
> main difference with integers is rejection of whitespace and
> toString-able objects.

So essentially we have a number of rules, which all are only slightly
different. And when somebody wants to skip spaces, but not tabs, we'd
have yet another set of functions? I don't think it's good for the
language to have a set of functions doing exactly the same, but in
slightly different way, because some people had different preferences.
The language should not be just a bag of use-cases that somebody wanted
to implement. We're getting a lot of criticism for parts of the language
not always playing cohesively together, why make it worse?

> The main point of the RFC is to add casting functions as an
> alternative to the built-in explicit casts. Currently, the easiest
> way to convert to an integer is (int), but this is quite dangerous as
> it performs no validation whatsoever and cannot fail. to_int() and

So, why not have filter_var($suspected_int, FILTER_VALIDATE_INT) and
filter_var($suspected_int, FILTER_CONVERT_INT)? We already have
infrastructure for that, why ignore it completely and build another
solution that does exactly the same but treats whitespace differently
and has couple of other tweaks? OK, you want to treat the whitespace
differently, I get it - but why ignore whole filter infrastructure?

> the like are intended to be just as convenient as an explicit cast,
> so that doing the safer thing (failing on garbage input) is not any
> more difficult. The hope is that the lazy developer will use `is_int()`
> instead of (int) when they need to explicitly cast, and  avoid the
> problems of the latter.

The lazy developer won't check the return value anyway and would get 0
as the result of false-to-int conversion, thus making the whole exercise
pointless anyway :)
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #78169 — Andrea Faulds — 2014-10-21T01:17:21+00:00

URL: https://externals.io/message/78160#78169 · In reply to: #78167

> 
> 
> Throwing an exception or even returning `NULL` seems so much better than returning "false" -- "false" is a boolean, not an error, and despite some historical cases of PHP using "false" as a poor person's error code, it really isn’t.

Why isn’t `FALSE` an error value? `NULL` signifies an absence of a value, not a bad value. We use `FALSE` in a lot of places to indicate an error. Heck, filter_var uses it for errors here.

> If you want error codes, use error codes, or use exceptions, but having two kinds of failure, null vs false, is really confusing.

What two kinds of error? We’re only using `FALSE` here.

> > […]
> 
> Throwing an exception also addresses this, in a much cleaner way. If you're worried about strict typing, then returning "false" is even worse, since the return type of, for example, to_int is now "int | bool" as opposed to "nullable-int" or "int" (if you throw).

Exceptions make chaining more difficult. There’s also no precedent for using them.

Returning `NULL` would mean it’s validate for a nullable type hint, which is bad, but also, `NULL` signifies a lack of a value. There isn’t a lack of a value, there’s no value. We should not use `NULL` here.

> > […]
> 
> Since this is a new function, one that doesn't interoperate in any complicated way with the existing library or affect BC, this doesn't seem that important. IMO a language should have one failure/absense-of-value, in most cases "null", and having a weird second case seems, well, weird.

Failure and absence of value are different things and should not use the same value. Otherwise, you are liable to confuse missing data and errors.

> If you have more interesting failure cases, just throw an exception, or return null if you want, don't continue propagating a weird second kind of null (that isn't actually null, it's a boolean false).

It’s not a “weird second kind of null”, it’s a value FALSE.

> Also, that we *couldn't* introduce a meaningful to_bool function, even if we decided we wanted it, indicates to me that returning false is the wrong thing to do.

It would be possible to use a special value in that specific case. Though, again, booleans have their own problems. I don’t see the point in to_bool().

> It's also interesting to look at how other languages handle failures of this kind. Most imperative languages I know of either throw or return null; in particular, Python, which has fairly similar type system to PHP in a lot of ways, throws. Functional languages do more interesting things; Haskell does something complicated but morally equivalent to returning null. But I'm not aware of any language which specifically returns false.

JavaScript returns NaN here and C sets errno to an error value. PHP uses FALSE, in some respects, like JavaScript uses NaN.

--
Andrea Faulds
http://ajf.me/

---

## #78170 — Andrea Faulds — 2014-10-21T01:32:29+00:00

URL: https://externals.io/message/78160#78170 · In reply to: #78168

> 
> 
> > […]
> 
> So essentially we have a number of rules, which all are only slightly
> different. And when somebody wants to skip spaces, but not tabs, we'd
> have yet another set of functions?

No, not quite. One of the nice things about rejecting whitespace is it lets you handle it however you want. Want to reject all whitespace? to_int($foo). Want to accept all whitespace? to_int(trim($foo)). Want to trim only tabs? to_int(trim($foo, “\t”)). This is actually allows more flexibility than filter_var does with its maze of flags.
> 
> > […]
> 
> So, why not have filter_var($suspected_int, FILTER_VALIDATE_INT) and
> filter_var($suspected_int, FILTER_CONVERT_INT)? We already have
> infrastructure for that, why ignore it completely and build another
> solution that does exactly the same but treats whitespace differently
> and has couple of other tweaks? OK, you want to treat the whitespace
> differently, I get it - but why ignore whole filter infrastructure?

It would be possible to make to_int() merely an alias of filter_var(…, FILTER_VALIDATE_INT). Though that would make it depend on ext/filter or otherwise duplicate functionality.

Also, treating whitespace differently wasn’t actually my idea. I’m perfectly fine with ignoring it, but Nikita convinced me I shouldn’t tolerate it. He has a point - it opens more possibilities than allowing it.

> > […]
> 
> The lazy developer won't check the return value anyway and would get 0
> as the result of false-to-int conversion, thus making the whole exercise
> pointless anyway :)

Not quite. With strict type hints, `FALSE` would fail for an integer parameter. Even without them, this still makes validation more straightforward. I suppose there are varying degrees of laziness.

--
Andrea Faulds
http://ajf.me/

---

## #78171 — Stas Malyshev — 2014-10-21T01:48:31+00:00

URL: https://externals.io/message/78160#78171 · In reply to: #78170

Hi!

> No, not quite. One of the nice things about rejecting whitespace is
> it lets you handle it however you want. Want to reject all
> whitespace? to_int($foo). Want to accept all whitespace?
> to_int(trim($foo)). Want to trim only tabs? to_int(trim($foo, “\t”)).
> This is actually allows more flexibility than filter_var does with
> its maze of flags.

This looks like "if you don't like my rules, you can easily apply string
handling functions to implement any rule you like". Which makes total
sense, except if I wanted to play with string handling functions, why
not just write a regexp and be done with it? Of course you can do any
transformation you like to the data, but if you propose it as a default
solution, then "you can add more transformations" is not an advantage -
you could always do that.

> It would be possible to make to_int() merely an alias of
> filter_var(…, FILTER_VALIDATE_INT). Though that would make it depend
> on ext/filter or otherwise duplicate functionality.

You seem to sound like depending on something already existing in PHP is
a bad thing.

> Also, treating whitespace differently wasn’t actually my idea. I’m
> perfectly fine with ignoring it, but Nikita convinced me I shouldn’t
> tolerate it. He has a point - it opens more possibilities than
> allowing it.

The point is not whether ignore or not ignore the whitespace. The point
is that having multiple APIs doing the same but differing in one small
detail because somebody thinks this detail is not exactly to his liking
in existing API - IMO is not a good thing.

> Not quite. With strict type hints, `FALSE` would fail for an integer

PHP is not a strictly typed language, so arguing as if it were or just
about to become one doesn't sound like a very good selling point. For
me, it exactly the reverse - you're emphasizing the fact that for it to
work, you need to change the whole nature of PHP not being a strictly
typed language.

> parameter. Even without them, this still makes validation more
> straightforward. I suppose there are varying degrees of laziness.

I'm not sure how using function starting with to_ is "more
straightforward" than using function starting with filter_ - which seems
to be the only thing different here. Except, of course, for whitespace
handling. Which in my opinion, still does not explain why we should
ignore existing API and create a completely new one.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #78185 — Dmitry Stogov — 2014-10-21T09:14:49+00:00

URL: https://externals.io/message/78160#78185 · In reply to: #78160

Both, the idea and implementation look fine.

Personally, I hate the existing type conversion rules, and I would like to
use something like this by default (may be with exception for
null/false/true handling), but it may be a big compatibility break, so
introducing to_int() is better than nothing.

some notes:
- it's probably make sense to implement these function as a new opcode(s)
in VM
- in case of conversion failure it's better to throw exception (to_int()
returning `FALSE` is a pain).

Thanks. Dmitry.



> Good evening,
>
> I am presenting a new RFC to add a set of three functions to do validated
> casts for scalar types:
>
> https://wiki.php.net/rfc/safe_cast
>
> Please read it.
>
> Thanks!
> --
> Andrea Faulds
> http://ajf.me/

---

## #78204 — Alexander Lisachenko — 2014-10-21T14:57:00+00:00

URL: https://externals.io/message/78160#78204 · In reply to: #78185

Hello, internals!

> Good evening,
>
> I am presenting a new RFC to add a set of three functions to do validated casts for scalar types:
>
> https://wiki.php.net/rfc/safe_cast
>
> Please read it.

Personally I don't like this RFC because it's introducing one more way
to cast value in PHP. We already have `boolval()`, `intval()`, strlva()
functions that are not widely used in the source code, because of
dynamic nature of PHP. Developers just use value as is, assuming that
it will cast automatically where needed. This kind of casting is
typically used to prevent an attacks like this $id =
intval($_GET['id']); But this is ugly implementation from my point of
view. Binding and sanitization can do this much better.

There is also one more way to cast values with explicit casting: $id =
(int) $_GET['id']. I think that this way of doing casting is more
natural for developers to read, because many languages use the same
scheme to cast values into another types. Instead of implementing new
to_xxxx() functions, it can be nice to reuse logic of casting with
"(type) $value" to follow
https://wiki.php.net/rfc/scalar_type_hinting_with_cast#conversion_rules
which looks great.

Besides this, there is casting with settype($value, $type) and one
more with filter sanitization.

If this RFC will be accepted there will be one more way with own logic
of casting. And this is not so good from userland point of view.

It can be good only with OOP support for primitive types, for example
$value = '1234'; $number = $value->toInt(); $float =
$value->toFloat(), etc..

Thanks!

---

## #78205 — Derick Rethans — 2014-10-21T15:26:14+00:00

URL: https://externals.io/message/78160#78205 · In reply to: #78160

> Good evening,
> 
> I am presenting a new RFC to add a set of three functions to do validated casts for scalar types:
> 
> https://wiki.php.net/rfc/safe_cast
> 
> Please read it.

> > […]

But what about if we also would like a to_bool, which would accept 
"true", "false", "0", "1", true, false, 1 and 0?

Then to_bool() whould return false... or true? So hence, it should be 
NULL, and that would also be consistent with ext/filter.

cheers,
Derick

---

## #78209 — Josh Watzman — 2014-10-21T18:22:07+00:00

URL: https://externals.io/message/78160#78209 · In reply to: #78169

> > […]
> 
> Why isn’t `FALSE` an error value? `NULL` signifies an absence of a value, not a bad value. We use `FALSE` in a lot of places to indicate an error. Heck, filter_var uses it for errors here.

 `FALSE` is not an error value because it is already something else. It's already a value, it's boolean false. The fact that you couldn't build a reasonable to_bool even if you wanted to, as I as well as others pointed out on this thread, indicates the very real problem with the conflation of purposes here. Derick Rethans said it pretty well:

> Then to_bool() whould return false... or true? So hence, it should be 
> NULL, and that would also be consistent with ext/filter.

You also said:

> > […]
> 
> It would be possible to use a special value in that specific case. Though, again, booleans have their own problems. I don’t see the point in to_bool().

Whether or not we actually should add to_bool is a separate issue; we, in principle, should be able to cleanly add it, since it's a very natural extension to what you've already designed here. The fact that, if we used `FALSE` for error that to_bool would have to be a special case, inconsistent with the rest, indicates to me that using `FALSE` is the wrong thing -- again, it's the conflation of the boolean value FALSE, which already has this meaning, with some error code. It shouldn't be conflated, `FALSE` should not be an error return, it means something else.

> > […]
> 
> What two kinds of error? We’re only using `FALSE` here.

But `FALSE` *is* a different kind of error as you're trying to use it here, different than `NULL` which is specifically designed to be an error / lack of value. `NULL` doesn't mean anything else, it's a specially-designated value. And if you don't want to use `NULL` for failure because you don't think this is quite the sort of failure that `NULL` expresses, then throw an exception -- `FALSE` is just totally the wrong thing to return.

> > […]
> 
> Exceptions make chaining more difficult. There’s also no precedent for using them.

I think the argument about chaining was addressed by someone else. With precedent, just because there's no precedent doesn't mean we can't start now :) They really feel like the right thing to do here and elsewhere, and we have to start somewhere.

> > […]
> 
> Failure and absence of value are different things and should not use the same value. Otherwise, you are liable to confuse missing data and errors.

But if you want to make that distinction, then you shouldn't use a value that means something else to indicate failure. You should throw an exception. Returning `FALSE` is liable to replace confusion between missing data and errors with confusion between some other data (i.e., the boolean FALSE) and errors.

I might also argue that missing the data makes it clear there was an error, and then if someone has a nullable typehint they expressly said they accept a lack-of-int, but an exception seems a much cleaner way to deal with this anyways.

> > […]
> 
> It’s not a “weird second kind of null”, it’s a value FALSE.

Which is being used as a weird second kind of failure, as opposed to `NULL` which is the typical failure lack-of-value, as I argue above.

> > […]
> 
> JavaScript returns NaN here and C sets errno to an error value. PHP uses FALSE, in some respects, like JavaScript uses NaN.

But it probably shouldn't -- NaN is a special number which is not a number (and which *would* probably pass a float type annotation, no?). `FALSE` isn't a special integer which isn't an integer -- it is already something else, it's a boolean. JS has a few special values which are specifically designated as different failures or lack-of-values -- undefined, null, NaN, etc. PHP's `FALSE` does *not* fall into that category -- it *does* mean something, it means something else, the boolean value false. (FWIW, I don't think that the way JS does this feels quite right either, I don't like that there are multiple sorts of non-exception failure values, but at least they return a designated failure value that doesn't have another totally different non-error meaning.)

Josh Watzman

---

## #78211 — Rowan Collins — 2014-10-21T20:56:54+00:00

URL: https://externals.io/message/78160#78211 · In reply to: #78171

> > […]
> You seem to sound like depending on something already existing in PHP is
> a bad thing.
>

I think the point was that ext/filter extension is optional (its enabled 
by default, but not mandatory) whereas

> I'm not sure how using function starting with to_ is "more
> straightforward" than using function starting with filter_

As I mentioned in a previous thread, the design of ext/filter makes it 
feel like a Swiss Army knife when what I'm looking for is a pair of 
scissors - it will work, but I have to figure out how to select the 
right component (both a function and a filter type), and whether the 
other bits will get in my way (do I need to set any options? what is the 
actual return type?).

On the other hand, the myriad of options it provides covers off most of 
the issues in this discussion, so maybe that complexity is the price you 
pay for pleasing all the people, and it's just a matter of documentation.

-- 
Rowan Collins
[IMSoP]

---

## #78214 — Andrea Faulds — 2014-10-21T22:51:11+00:00

URL: https://externals.io/message/78160#78214 · In reply to: #78185

> 
> 
> some notes:
> - it's probably make sense to implement these function as a new opcode(s) in VM

That could be an optimisation later, yes. I note that you’ve added function replacement with opcodes for certain commonly-used functions. We could make these functions use that. Then they’d still be usable as callbacks.

> - in case of conversion failure it's better to throw exception (to_int() returning `FALSE` is a pain).

I am gradually warming to throwing an exception. An interesting idea I’ve had suggested on Twitter was by Matt Parker, who suggested that I add an optional 2nd argument. Without the argument, it throws an exception. With an argument, it returns that value (as a default) instead of throwing an exception.

--
Andrea Faulds
http://ajf.me/

---

## #78215 — Andrea Faulds — 2014-10-21T22:53:01+00:00

URL: https://externals.io/message/78160#78215

> 
> 
> 
> > […]
> 
> You might want to consider re-wording that. It comes across as rather an oxymoron…

Oh dear, I repeated myself accidentally. I think I meant to say, “There isn’t a lack of a value, there’s a bad value”.
--
Andrea Faulds
http://ajf.me/

---

## #78216 — Dmitry Stogov — 2014-10-22T07:45:59+00:00

URL: https://externals.io/message/78160#78216 · In reply to: #78214

>
> > […]
> opcode(s) in VM
>
> That could be an optimisation later, yes. I note that you’ve added
> function replacement with opcodes for certain commonly-used functions. We
> could make these functions use that. Then they’d still be usable as
> callbacks.
>

I may help with implementation, if RFC accepted.
(It would be better if ZEND_STRLEN, ZEND_TYPE_CHECK, etc were introduced in
first place instead of stlen(), `is_long()` and family).



> > […]
> returning `FALSE` is a pain).
>
> I am gradually warming to throwing an exception. An interesting idea I’ve
> had suggested on Twitter was by Matt Parker, who suggested that I add an
> optional 2nd argument. Without the argument, it throws an exception. With
> an argument, it returns that value (as a default) instead of throwing an
> exception.
>

Together with https://wiki.php.net/rfc/engine_exceptions_for_php7 throwing
exceptions would be the best choice. I would make it permanent, (without
optional areguments)

Thanks. Dmitry.


>
> --
> Andrea Faulds
> http://ajf.me/

---

## #78218 — Lester Caine — 2014-10-22T08:07:54+00:00

URL: https://externals.io/message/78160#78218 · In reply to: #78214

> I am gradually warming to throwing an exception. An interesting idea I’ve had suggested on Twitter was by Matt Parker, who suggested that I add an optional 2nd argument. Without the argument, it throws an exception. With an argument, it returns that value (as a default) instead of throwing an exception.

Now that sounds like a nice compromise in a few places where exceptions
have been introduced, but I still think this is still a little chicken
and egg. If it is going to 'fail' then the reason for the failure is
more important than simply producing no answer. Especially if it is
going to fail in different inputs to other methods.

Again forcing an exception only solution sidesteps that debate!

-- 
Lester Caine - G8HFL
-----------------------------
Contact - http://lsces.co.uk/wiki/?page=contact
L.S.Caine Electronic Services - http://lsces.co.uk
EnquirySolve - http://enquirysolve.com/
Model Engineers Digital Workshop - http://medw.co.uk
Rainbow Digital Media - http://rainbowdigitalmedia.co.uk

---

## #78220 — Stas Malyshev — 2014-10-22T08:17:47+00:00

URL: https://externals.io/message/78160#78220 · In reply to: #78216

Hi!

> > […]

If those are opcodes, those rules will require 2/3 majority for
acceptance, since those will be the engine rules for type conversion,
not just a set of functions. And, of course, the rules not matching the
other engine rules for type conversion, sorry for sounding like broken
record.

-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #78221 — Zeev Suraski — 2014-10-22T08:26:16+00:00

URL: https://externals.io/message/78160#78221 · In reply to: #78220

> -----Original Message-----
> From: Stas Malyshev [mailto:smalyshev@sugarcrm.com]
> Sent: Wednesday, October 22, 2014 11:18 AM
> To: Dmitry Stogov; Andrea Faulds
> Cc: PHP Internals
> Subject: Re: [PHP-DEV] [RFC] Safe Casting Functions
>
> Hi!
>
> > […]
>
> If those are opcodes, those rules will require 2/3 majority for
> acceptance,
> since those will be the engine rules for type conversion, not just a set
> of
> functions. And, of course, the rules not matching the other engine rules
> for
> type conversion, sorry for sounding like broken record.

Regardless of how we implement it, this requires a 2/3 majority - it'll be
perceived as an integral part of the core language in the same way that
 `gettype()` and `is_array()` are considered parts of the core language.
Introducing a new set of typing rules into PHP cannot be a 50%+1 decision.

Zeev

---

## #78222 — Zeev Suraski — 2014-10-22T08:34:27+00:00

URL: https://externals.io/message/78160#78222

> -----Original Message-----
> From: Zeev Suraski [mailto:zeev@zend.com]
> Sent: Wednesday, October 22, 2014 11:26 AM
> To: 'Stas Malyshev'; 'Andrea Faulds'
> Cc: 'PHP Internals'
> Subject: RE: [PHP-DEV] [RFC] Safe Casting Functions
>
> > […]
> record.
>
> Regardless of how we implement it, this requires a 2/3 majority - it'll be
> perceived as an integral part of the core language in the same way that
> `gettype()` and `is_array()` are considered parts of the core language.
> Introducing a new set of typing rules into PHP cannot be a 50%+1 decision.

Thinking a bit more on this, if we don't want the 2/3 hurdle and perhaps
make this a bit (or actually a lot) less controversial, we should change the
names of these functions.  to_float() strongly implies that this function
represents PHP's standard typing ruleset, which these functions do not.

If we called them something like lossless_float() - that provides developers
with the necessary heads-up that this will not use the standard conversion
rules they're familiar with.  It also gives them a good indication as to how
it may be different from those standard rules.

Changing the function names in a way that makes it clear that they don't
represent the standard conversion rules, and providing a good hint as to how
these functions behave differently right within the function names - would
remove my objection to introducing these functions.  In such a context,
where they're not a part of the perceived core global namespace - I think
they can be considered like any other extension, and be at 50%+1.

Zeev

---

## #78223 — Bob Weinand — 2014-10-22T08:37:11+00:00

URL: https://externals.io/message/78160#78223 · In reply to: #78160

I know we have that already discussed a lot now, but I’d like to expose my points on the return value here:

I imagine code like (supposing that we ever will have scalar typehints):

function acceptsInt (int $i = null) {
    if ($i === null) {
        $i = 2 /* default value */;
    }
    /* do something with $i */
}

When we return false:
acceptInt(($tmp = to_int($_GET["userinput"])) === false ? null : $tmp);

When we throw an exception:
try {
    acceptInt(to_int($_GET["userinput"]));
} catch (CastingException $e) {
    acceptInt(null);
}

When we just return null:
acceptInt(to_int($_GET["userinput"]));

Also, when we want to pass a default value defined outside of the function, it’s a lot easier now with the coalesce operator:
acceptInt(to_int($_GET["userinput“]) ?? 2 /* default value */);


Also, independently of possible scalar typehints:

Generally exceptions are also a bad idea as the casts probably will be used on external input and exceptions are **not** a way to handle malformed user input. Really not.
Furthermore, false is a bad idea in the same sense (if we get scalar type hints once), because people then might just catch the EngineException…

Also, null means "no value"; that’s exactly what we need. If the to_{type}() functions cannot return a meaningful value, just return "no value", that means null. And not false, which is a real value.

That’s why I strongly feel that null is the only true thing to return here.

Thanks,
Bob

> Am 21.10.2014 um 00:57 schrieb Andrea Faulds <ajf@ajf.me>:
> 
> Good evening,
> 
> I am presenting a new RFC to add a set of three functions to do validated casts for scalar types:
> 
> https://wiki.php.net/rfc/safe_cast
> 
> Please read it.
> 
> Thanks!
> --
> Andrea Faulds
> http://ajf.me/

---

Next page: https://externals.io/message/78160.md?page=2
