# [RFC] Scalar Type Hinting With Casts (re-opening)

- Thread: https://externals.io/message/75383
- Original archive: https://news-web.php.net/php.internals/75383
- Started by Andrea Faulds on 2014-07-13T01:57:28+00:00
- Messages: 196
- Page 1 of 8: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/75383.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #75383 — Andrea Faulds — 2014-07-13T01:57:28+00:00

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

Good evening,

PHP’s type hinting system is rather incomplete as it does not support scalars, only arrays, callables and objects. In 2012, Anthony Ferrara created an RFC which proposed type hinting for scalar types (int, float, bool, string and resource) with casting, with behaviour nearly the same as that of zend_parse_parameters. Sadly, he later left PHP internals and withdrew his RFCs.

Since I am very much in favour of scalar type hints, I’ve updated the patch to master and made some minor improvements, and I am re-opening the RFC with the intent to try and get it into PHP 5.7. The patch is mostly there. It needs some more tests and there are some edge cases I need to deal with, but it otherwise works, and I expect I can finish fixing it up very soon.

The RFC is here: https://wiki.php.net/rfc/scalar_type_hinting_with_cast

A pull request is here: https://github.com/php/php-src/pull/717

I’m hoping I can get this into PHP 5.7. I think scalar type hinting would be a valuable addition to PHP’s existing type hinting system.

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

---

## #75384 — Stas Malyshev — 2014-07-13T05:22:22+00:00

URL: https://externals.io/message/75383#75384 · In reply to: #75383

Hi!

> PHP’s type hinting system is rather incomplete as it does not support
> scalars, only arrays, callables and objects. In 2012, Anthony Ferrara
> created an RFC which proposed type hinting for scalar types (int,
> float, bool, string and resource) with casting, with behaviour nearly
> the same as that of zend_parse_parameters. Sadly, he later left PHP
> internals and withdrew his RFCs.

I have one request: could we please stop calling it "hinting"?
The dictionary says (http://www.thefreedictionary.com/hint) that
the word "hint" means:

1. A slight indication or intimation: wanted to avoid any hint of scandal.
2.
a. A brief or indirect suggestion; a tip: stock-trading hints.
b. A statement conveying information in an indirect fashion; a clue:
Give me a hint about the big news.
3. A barely perceptible amount: just a hint of color.

What we have in PHP and what is being proposed it not a "slight
indication", not "suggestion" and not "conveying information in indirect
fashion" (what Python does in PEP-3107 could be called that way, but
it's not what is proposed here). It is very direct specification of
either strict parameter typing or coercive parameter typing. I don't
think using confusing terminology helps anything here. I think it was a
mistake to introduce this term from the start and we should stop
propagating it.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #75385 — Lester Caine — 2014-07-13T08:16:33+00:00

URL: https://externals.io/message/75383#75385 · In reply to: #75384

> It is very direct specification of
> either strict parameter typing or coercive parameter typing. I don't
> think using confusing terminology helps anything here. I think it was a
> mistake to introduce this term from the start and we should stop
> propagating it.

It does come across as as an attempt to hide the 'strict parameter
typing' which is something that is very much less attractive. If I
wanted that then I'd simply switch back to C/C++ direct which is perhaps
where we are now heading anyway with the increasing use of pre-compiled
application code?

One of the reasons I persist with PHP is the fact that many of my users
can adjust the odd PHP file correcting sequence or modifying text
without having to learn the intricacies of formal programming. It's
adding all these complex layers that is taking PHP away from it's more
novice friendly base ... If you want a formal programming language then
just use one?

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

---

## #75386 — Philip Sturgeon — 2014-07-13T10:17:31+00:00

URL: https://externals.io/message/75383#75386 · In reply to: #75385

> 
> > […]
>
> It does come across as as an attempt to hide the 'strict parameter
> typing' which is something that is very much less attractive. If I
> wanted that then I'd simply switch back to C/C++ direct which is perhaps
> where we are now heading anyway with the increasing use of pre-compiled
> application code?
>
> One of the reasons I persist with PHP is the fact that many of my users
> can adjust the odd PHP file correcting sequence or modifying text
> without having to learn the intricacies of formal programming. It's
> adding all these complex layers that is taking PHP away from it's more
> novice friendly base ... If you want a formal programming language then
> just use one?
>
> --
> 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
>
> --
> 
> 
>

Type hinting worked as a phrase when classes, interfaces a traits were
the majority of what was going on. The fact that I can say I would
like a Foo and get a Bar (which extends or implements Foo) means that
"hint" is a perfectly valid word to use.

If we move onto scalars theb you two are both right, "hint" is no
longer a hint. It is too strict for hint to work, as it is a way to
specifically ask for a certain piece of data.

Now, if we can accept that and move away from arguing semantics, there
is a more useful conversation to be had:

Should we have this thing, regardless of the name?


To paraphrase Lester Caine's last message: PHP can't have nice things.


His argument is one that I see repeatedly on internals: "If you want a
formal programming language then just use one?"

I think this misses the point of why many people (myself included) use
PHP. Despite PHP's various and extensive list of often rather comical
flaws, I continue to use PHP (and probably will for another decade)
because it is the most popular language on the internet. I can ship
something that can be downloaded and installed by drastically more
people than other languages. Until that situation changes, I build
software like PyroCMS, release packages like those on The League of
Extraordinary Packages, help write standards for the PHP-FIG, and do
it all with this crazy hodge-podge language we all know and "love."

If I had the choice of picking and choosing whichever language I
wanted to use all the time, I would be using Python, Ruby, Hack, Go,
or whatever language I felt like using that morning, and I often do.
Because I don't always get that choice, and because I legitimately
_am_ stuck with PHP, I do like to see it continue to grow and improve
over time.

I believe I am not unique in this regard.

I, like Lester, do not want to see PHP get more difficult over time,
just because I am growing as a developer over time and eventually want
more and more formal features in the language. Luckily that is not
what is being suggested here.


Type hinting (strict parameter typing) is not some crazy C/C++ only
feature that junior developers will be entirely baffled by. I assume
at some point if you but a "square" into a $circle then you will get
an error, or a warning, or some sort of "Hi, this is wrong." which
will either be gob-smackingly self explanatory, or a quick google
away.

People here have often suggested that googling an error is a solution,
like the fantastic defense of `T_PAAMAYIM_NEKUDOTAYIM` a few years back
(and multiple times before and after):

"Come on people, what exactly is the problem with a once-in-a-lifetime
investment of 5 seconds of your time to google some stupid error
message. Something you, as a developer, spend your life doing.
Please, stop complaining about a minor (yes, it is minor, use the
fricking search engine!) annoyance and accept php's heritage."

If googling error messages is used as a reason to keep completely
useless things like T_PAAMAYIM_NEKUDOTAYIM, then that same argument
cannot be used as a reason to block genuinely useful features. One or
the other folks.


If we can move forward without anyone else saying "AAAH THATS C++" (or
my other favorite "AAAH THATS JAVA") then it would be interesting to
hear how people feel about this article, which covers a lot of the
difficulties of type hinting parameters in PHP:

https://nikic.github.io/2012/03/06/Scalar-type-hinting-is-harder-than-you-think.html

I'm sure you've all read it of course, but I would be interested to
see which of you support which approach.

If we can (for now) continue to use "hinting" without accusations of
being sneaky, then the RFC is discussion uses "Casting weak type
hinting." I would not hate to see "Casting weak type hinting" used,
but would prefer "Strict weak type hinting" myself.

---

## #75387 — Alain Williams — 2014-07-13T10:18:40+00:00

URL: https://externals.io/message/75383#75387 · In reply to: #75385

> 
> > […]
> 
> It does come across as as an attempt to hide the 'strict parameter
> typing' which is something that is very much less attractive. If I
> wanted that then I'd simply switch back to C/C++ direct which is perhaps
> where we are now heading anyway with the increasing use of pre-compiled
> application code?
> 
> One of the reasons I persist with PHP is the fact that many of my users
> can adjust the odd PHP file correcting sequence or modifying text
> without having to learn the intricacies of formal programming. It's
> adding all these complex layers that is taking PHP away from it's more
> novice friendly base ... If you want a formal programming language then
> just use one?

I don't see the current PHP type juggling as 'formal programming'. It makes
things easy but can also lead to bugs where unexpected values (& so types) end
up being inappropriately used.

This RFC does not mandate the use of type hinting so your users can still get
away with quick/sloppy programming. That does not change.

However: it does allow others to gain extra assurance that their programs are
not dealing with bad values (& so types) if they wish to. I can see that the
first areas where this will be used will be in objects/libraries that others
use. It will be good to use type hinting to bring out bugs where a bad value has
slipped by validation. The users of such libraries would not need to make
changes as a result of this.

I can see that it will also allow run time optimisation. If a value is known to
contain an integer then code like ''$a == $b'' could be an integer comparison
rather than having to first determine what the types might be and then end up
doing integer compare.


So: I strongly support this RFC.


I would also like to suggest an addition. That is the ability to declare local
variables to functions maybe using the using the keyword 'var'. So you would go:

    function foo(int $a)
    {
        var $b;        // $b has no type hinting
	var float $c;  // $c is a float
	string $d;     // alternative to the syntax used for $c (see below)
    }

I would like, eventually, PHP to have a mode where use of an undeclared variable
would lead to an error being raised.  A model for this is perl's ''use strict''.
The way that this could be done in PHP is that if a variable is declared with
'var' then strict mode is switched on for the function.  This would provide a
distinction between the above declarations for $c and $d ($c switches on strict
mode, $d does not).

This would be OPTIONAL - ie if you do not want it then do not use 'var' and it
will not impinge; if you use it then you get the extra checking that it brings.

Should I raise an RFC for this ?

-- 
Alain Williams
Linux/GNU Consultant - Mail systems, Web sites, Networking, Programmer, IT Lecturer.
+44 (0) 787 668 0256  http://www.phcomp.co.uk/
Parliament Hill Computers Ltd. Registration Information: http://www.phcomp.co.uk/contact.php
#include <std_disclaimer.h

---

## #75388 — Andrea Faulds — 2014-07-13T10:58:58+00:00

URL: https://externals.io/message/75383#75388 · In reply to: #75384

> I have one request: could we please stop calling it "hinting"?
> The dictionary says (http://www.thefreedictionary.com/hint) that
> the word "hint" means:
> 
> 1. A slight indication or intimation: wanted to avoid any hint of scandal.
> 2.
> a. A brief or indirect suggestion; a tip: stock-trading hints.
> b. A statement conveying information in an indirect fashion; a clue:
> Give me a hint about the big news.
> 3. A barely perceptible amount: just a hint of color.
> 
> What we have in PHP and what is being proposed it not a "slight
> indication", not "suggestion" and not "conveying information in indirect
> fashion" (what Python does in PEP-3107 could be called that way, but
> it's not what is proposed here). It is very direct specification of
> either strict parameter typing or coercive parameter typing. I don't
> think using confusing terminology helps anything here. I think it was a
> mistake to introduce this term from the start and we should stop
> propagating it.

I agree that “type hinting” is a bad name for it. Perhaps “optional typing” would be better. It conveys that these specifiers are completely optional, and that there is a system of typing, but it doesn’t say anything about its strictness.

Regardless, this RFC will stick with the current terminology, but changing the terminology would be quite simple, you could just update the manual and possibly change some of the internal names.

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

---

## #75389 — Zeev Suraski — 2014-07-13T11:35:43+00:00

URL: https://externals.io/message/75383#75389 · In reply to: #75387

> I don't see the current PHP type juggling as 'formal programming'. It
makes
> things easy but can also lead to bugs where unexpected values (& so
types)
> end up being inappropriately used.

I haven't yet reviewed the conversion table in detail, but unless I'm
missing something, this RFC is in fact much more in the spirit of PHP -
and implements type juggling - unlike the previous incarnation of strict
typing that almost made it into PHP.  It's a bit too strict to my liking
(especially around conversion of floating point to int, which should pass
and perhaps generate a notice IMHO), but this is a big step towards the
spirit of what I proposed together with Lukas back in 2010
(https://wiki.php.net/rfc/typecheckingstrictandweak) - which was an
alternative to the strong typing suggested by several others.


Type juggling is an *inherent* feature of PHP.  Paraphrasing what Rasmus
said several years ago(*), 'if you implement this [strong typing], please
don't call it PHP'.

Again, luckily, what Andrea proposes isn't strong typing.  It still
maintains the most important properties of type juggling - e.g. the
ability to work with strings coming in as input (GET/POST/etc.) without
having to worry about typing.

Zeev

(*) I couldn't find that email quickly enough so apologies if I'm not
completely accurate on this.

---

## #75390 — Andrea Faulds — 2014-07-13T11:48:09+00:00

URL: https://externals.io/message/75383#75390 · In reply to: #75389

> I haven't yet reviewed the conversion table in detail, but unless I'm
> missing something, this RFC is in fact much more in the spirit of PHP -
> and implements type juggling - unlike the previous incarnation of strict
> typing that almost made it into PHP.  It's a bit too strict to my liking
> (especially around conversion of floating point to int, which should pass
> and perhaps generate a notice IMHO), but this is a big step towards the
> spirit of what I proposed together with Lukas back in 2010
> (https://wiki.php.net/rfc/typecheckingstrictandweak) - which was an
> alternative to the strong typing suggested by several others.
> 
> 
> Type juggling is an *inherent* feature of PHP.  Paraphrasing what Rasmus
> said several years ago(*), 'if you implement this [strong typing], please
> don't call it PHP'.
> 
> Again, luckily, what Andrea proposes isn't strong typing.  It still
> maintains the most important properties of type juggling - e.g. the
> ability to work with strings coming in as input (GET/POST/etc.) without
> having to worry about typing.

Right. I think this RFC would strengthen PHP’s weak typing guarantees, because while internal functions will convert to the right type and hence avoid issues with strings and such not acting quite like integers in some situations, userland functions usually don’t. This RFC would mean that, at least for “hinted” functions, user_land_function($_GET[‘id’]) should work just as well as internal_function($_GET[‘id’]).

Also, it’s not really “what Andrea proposes”, it’s Anthony’s proposal, even if he is sadly absent from the list these days. I’m just trying to fix up the patch, iron out remaining wrinkles, and get this into PHP.

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

---

## #75391 — Nikita Popov — 2014-07-13T12:09:42+00:00

URL: https://externals.io/message/75383#75391 · In reply to: #75383

> Good evening,
>
> PHP’s type hinting system is rather incomplete as it does not support
> scalars, only arrays, callables and objects. In 2012, Anthony Ferrara
> created an RFC which proposed type hinting for scalar types (int, float,
> bool, string and resource) with casting, with behaviour nearly the same as
> that of zend_parse_parameters. Sadly, he later left PHP internals and
> withdrew his RFCs.
>
> Since I am very much in favour of scalar type hints, I’ve updated the
> patch to master and made some minor improvements, and I am re-opening the
> RFC with the intent to try and get it into PHP 5.7. The patch is mostly
> there. It needs some more tests and there are some edge cases I need to
> deal with, but it otherwise works, and I expect I can finish fixing it up
> very soon.
>
> The RFC is here: https://wiki.php.net/rfc/scalar_type_hinting_with_cast
>
> A pull request is here: https://github.com/php/php-src/pull/717
>
> I’m hoping I can get this into PHP 5.7. I think scalar type hinting would
> be a valuable addition to PHP’s existing type hinting system.
>
> Thanks!
>

I think the approach described in this proposal is the best way to
implement scalar typehinting, as it allows typical loosely-typed usage
patterns, while still providing type guarantees within the function.

I haven't yet closely reviewed the details of what is and isn't allowed,
but one things I would strongly recommend against is introducing any
"accept but throw a notice" cases. Either a value is allowed or it isn't.
"12foo" to an int/float argument should throw a recoverable fatal error,
like everything else. (I'd change that in zpp as well, but that's a
different discussion).

The question of passing floats like 12.5 to an int param is somewhat
tricky. One could argue that it's possible to end up with floats like
12.0000000001, which are nearly integers but not quite there, and a user
might expect them to behave the same as the integer 12. On the other hand
one can also argue that it's easy to end up with the inverse, namely
11.999999999999. In this case the end user might also expect it to be
treated as integer 12, however an integer cast will truncate it to 11.

The truncation behavior of the float to int cast is why I tend towards the
behavior the RFC currently proposes (forbid non-integral floats): It is
rather unlikely that truncation is what was intended, as such an explicit
rounding call is necessary anyways.

Nikita

---

## #75392 — Jocelyn Fournier — 2014-07-13T12:50:09+00:00

URL: https://externals.io/message/75383#75392 · In reply to: #75391

Hi,

Would it possible to control the implicit casting through a PHP variable 
? (or perhaps modify `E_STRICT` to display a warning if this kind of 
implicit cast is done ?)
I mean specifying explicitly a type is often useful to make sure the 
proper type is passed to the function, and there's no bug in the calling 
func.

e.g. safety check like

function foo($bar) {
    if (!is_int($bar)) {
       throw new Exception('Invalid parameter type');
    }
}

will not be "equivalent" to

function foo(int $bar) {

}

and there will be no way to have an equivalent behaviour once "type 
hinting" is used !


Thanks,
   Jocelyn


Le 13/07/2014 14:09, Nikita Popov a écrit :
> 
>
> > […]
>
> I think the approach described in this proposal is the best way to
> implement scalar typehinting, as it allows typical loosely-typed usage
> patterns, while still providing type guarantees within the function.
>
> I haven't yet closely reviewed the details of what is and isn't allowed,
> but one things I would strongly recommend against is introducing any
> "accept but throw a notice" cases. Either a value is allowed or it isn't.
> "12foo" to an int/float argument should throw a recoverable fatal error,
> like everything else. (I'd change that in zpp as well, but that's a
> different discussion).
>
> The question of passing floats like 12.5 to an int param is somewhat
> tricky. One could argue that it's possible to end up with floats like
> 12.0000000001, which are nearly integers but not quite there, and a user
> might expect them to behave the same as the integer 12. On the other hand
> one can also argue that it's easy to end up with the inverse, namely
> 11.999999999999. In this case the end user might also expect it to be
> treated as integer 12, however an integer cast will truncate it to 11.
>
> The truncation behavior of the float to int cast is why I tend towards the
> behavior the RFC currently proposes (forbid non-integral floats): It is
> rather unlikely that truncation is what was intended, as such an explicit
> rounding call is necessary anyways.
>
> Nikita

---

## #75393 — Andrea Faulds — 2014-07-13T12:56:08+00:00

URL: https://externals.io/message/75383#75393 · In reply to: #75392

> Would it possible to control the implicit casting through a PHP variable ? (or perhaps modify `E_STRICT` to display a warning if this kind of implicit cast is done ?)

No. I mean, yes, it’s possible, but allowing the effective function signature of a function to change based on some variable or ini setting does not sound like a good idea to me.

> I mean specifying explicitly a type is often useful to make sure the proper type is passed to the function, and there's no bug in the calling func.
> 
> e.g. safety check like
> 
> function foo($bar) {
>   if (!is_int($bar)) {
>      throw new Exception('Invalid parameter type');
>   }
> }
> 
> will not be "equivalent" to
> 
> function foo(int $bar) {
> 
> }
> 
> and there will be no way to have an equivalent behaviour once "type hinting" is used !

You just demonstrated one:

> function foo($bar) {
>   if (!is_int($bar)) {
>      throw new Exception('Invalid parameter type');
>   }
> }

If you really want to continue doing that, nothing would stop you.
--
Andrea Faulds
http://ajf.me/

---

## #75395 — Andrea Faulds — 2014-07-13T13:17:54+00:00

URL: https://externals.io/message/75383#75395

> Actually displaying a warning in `E_STRICT` but still doing the implicit cast would not change the function signature.

Sure. What I meant was more that we’re changing expectations based on php.ini/variable/etc., and I’d rather it’s always consistent.

> 
> Indeed :) But I have also performances in mind. Usually (at least in HACK / Zephir), "type hinting" is used to help the compiler optimize the code. If this type hinting could be useful to help my code working in a futur PHP->PECL compiler, or help the PHP opcache to do some optimisations, I'd like to use "type hinting" as much as possible.
> 
> But with the above limitation, I'll not be able to do so.

I think this type hinting wouldn’t hinder optimisation. Casting means that it’s still guaranteed that the value you get is of the requested type.

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

---

## #75396 — Alain Williams — 2014-07-13T13:20:42+00:00

URL: https://externals.io/message/75383#75396 · In reply to: #75389

> Type juggling is an *inherent* feature of PHP.  Paraphrasing what Rasmus
> said several years ago(*), 'if you implement this [strong typing], please
> don't call it PHP'.
> 
> Again, luckily, what Andrea proposes isn't strong typing.  It still
> maintains the most important properties of type juggling - e.g. the
> ability to work with strings coming in as input (GET/POST/etc.) without
> having to worry about typing.

I think that you need to look at how and where this will be used. In (what I
shall call) the outer parts of programs it may not be useful, but it will in the
inner parts.

Let me explain:

The outer part of a program which will work with things like $_GET['age'] which
might have values like: '10', 'ten', '10.5', '' or even be unset. Even assigning
a value to '$age' and have PHP do type checking is not what you want.

Type juggling is an important part of outer code.

Input (form) variables are then type/... checked by validation tests, this will
reject 'ten', '', unset and maybe '10.5'. I see this as a kind of firewall.

The inner side only uses values that have been through the 'firewall', ie I know
that $age will contain an integer. I can then do integer operations on it
without further checking - indeed I do NOT want to have to do further checking
since that just adds to the code size/complexity/ugliness.

It is in this 'inner' code where I will want to use PHP type hinting as
currently discussed. Although my values should have been though the firewall, I
do make mistakes, etc, so the inner code either occasionally fails in an obscure
way or assertions are done. Some means of having PHP help here would be very much
appreciated.

Which of the two below is clearer:

    function CanDrive($age)
    {
        if( !is_numeric($age))
	    throw new Error("\$age is not integer (CanDrive())");

	return $age >= 17;
    }

    function CanDrive(int $age)
    {
	return $age >= 17;
    }


The above is how I write programs. [I do realise that the 2 above are not
exactly the same.]

> (*) I couldn't find that email quickly enough so apologies if I'm not
> completely accurate on this.

-- 
Alain Williams
Linux/GNU Consultant - Mail systems, Web sites, Networking, Programmer, IT Lecturer.
+44 (0) 787 668 0256  http://www.phcomp.co.uk/
Parliament Hill Computers Ltd. Registration Information: http://www.phcomp.co.uk/contact.php
#include <std_disclaimer.h

---

## #75398 — Andrea Faulds — 2014-07-13T13:58:29+00:00

URL: https://externals.io/message/75383#75398

> Ok, in this case I would suggest always displaying a warning in `E_STRICT` since it's the whole purpose of the strict mode :)

Isn’t `E_STRICT` more for compile-time stuff? I’d think `E_NOTICE` would be the appropriate type here.

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

---

## #75399 — Andrea Faulds — 2014-07-13T14:20:43+00:00

URL: https://externals.io/message/75383#75399 · In reply to: #75391

> I haven't yet closely reviewed the details of what is and isn't allowed,
> but one things I would strongly recommend against is introducing any
> "accept but throw a notice" cases. Either a value is allowed or it isn't.
> "12foo" to an int/float argument should throw a recoverable fatal error,
> like everything else. (I'd change that in zpp as well, but that's a
> different discussion).

I’ve changed this case in the RFC and my patch. Previously, “12foo” would just throw an E_NOTICE, but now it is not accepted:

Integer hints:

function foo(int $a) {
    var_dump($a); 
}
foo(1); // int(1)
foo("1"); // int(1)
foo(1.0); // int(1)
foo("1a"); // `E_RECOVERABLE_ERROR` 
foo("a"); // `E_RECOVERABLE_ERROR` 
foo(999999999999999999999999999999999999); // `E_RECOVERABLE_ERROR` (since it's not exactly representable by an int)
foo(1.5); // `E_RECOVERABLE_ERROR` 

Float hints:

function foo(float $a) {
    var_dump($a); 
}
foo(1); // float(1)
foo("1"); // float(1)
foo(1.0); // float(1)
foo("1a"); // `E_RECOVERABLE_ERROR` 
foo("a"); // `E_RECOVERABLE_ERROR` 
foo(1.5); // float(1.5)

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

---

## #75400 — Zeev Suraski — 2014-07-13T14:21:59+00:00

URL: https://externals.io/message/75383#75400 · In reply to: #75396

> Which of the two below is clearer:
>
>     function CanDrive($age)
>     {
>         if( !is_numeric($age))
> 	    throw new Error("\$age is not integer (CanDrive())");
>
> 	return $age >= 17;
>     }
>
>     function CanDrive(int $age)
>     {
> 	return $age >= 17;
>     }

I think we're on the same page here that the 2nd one looks better, which
is the point of the RFC.

But the way I see it, the RFC should focus pretty much exclusively on
sanitizing information coming from the 'outer code' and into the 'inner
code', as opposed to enforcing strict typing within the inner code (a
function that unless I'm missing something it does not attempt to do,
thankfully).

The point of the RFC is that as the author of the API, you wouldn't have
to worry about input sanity, while still allowing the dynamic nature of
PHP - AKA type juggling - so that users who call that API don't need to be
bothered with the mechanics of their types either.

Zeev

---

## #75402 — Zeev Suraski — 2014-07-13T14:29:54+00:00

URL: https://externals.io/message/75383#75402 · In reply to: #75391

> I haven't yet closely reviewed the details of what is and isn't allowed,
> but one
> things I would strongly recommend against is introducing any "accept but
> throw a notice" cases. Either a value is allowed or it isn't.
> "12foo" to an int/float argument should throw a recoverable fatal error,
> like
> everything else. (I'd change that in zpp as well, but that's a different
> discussion).

The use case of converting string based values into integers and floating
point numbers is a very common one, given anything that comes into PHP as
input is a string.  In terms of productivity, it's much easier for me to
stick an 'int' type hint (or whatever we call it) on a piece of $_GET value
that I know needs to be an integer, than it is for me to now surround it in
a try/catch block and protect against a user or a wannabe hacker sending in
'123abc' in there.  In such a case treating this as 123 (int) makes perfect
sense, with the erroneous input silently converted to something sane the
code can live with.  A key advantage of these casting type hints is saving
the need to write lengthy and somewhat obscure pieces of code that just
validate inputs.  If we force developers to surround them with try/catch
blocks, we lose at least half of the value here IMHO.

I therefore think conversion from string to any of the basic types should
never result in an exception even if information is lost;  And it does make

> The question of passing floats like 12.5 to an int param is somewhat
> tricky.
> One could argue that it's possible to end up with floats like
> 12.0000000001,
> which are nearly integers but not quite there, and a user might expect
> them
> to behave the same as the integer 12. On the other hand one can also argue
> that it's easy to end up with the inverse, namely 11.999999999999. In this
> case the end user might also expect it to be treated as integer 12,
> however an
> integer cast will truncate it to 11.
>
> The truncation behavior of the float to int cast is why I tend towards the
> behavior the RFC currently proposes (forbid non-integral floats): It is
> rather
> unlikely that truncation is what was intended, as such an explicit
> rounding call
> is necessary anyways.

I'm undecided on this one too.

Zeev

---

## #75403 — Zeev Suraski — 2014-07-13T14:31:41+00:00

URL: https://externals.io/message/75383#75403 · In reply to: #75399

I think this is a big step in the wrong direction to one of the most
common auto-conversion use cases out there (HTTP input variables).  See my
note to Nikita...

This RFC is a huge deal, I suggest we let more people voice their opinion
in before changing it in each direction :)

Zeev

> -----Original Message-----
> From: Andrea Faulds [mailto:ajf@ajf.me]
> Sent: Sunday, July 13, 2014 5:21 PM
> To: Nikita Popov
> Cc: PHP internals
> Subject: Re: [PHP-DEV] [RFC] Scalar Type Hinting With Casts (re-opening)
>
>
> 
>
> > […]
allowed
> or it isn't.
> > […]
>
> I've changed this case in the RFC and my patch. Previously, "12foo"
would just
> throw an E_NOTICE, but now it is not accepted:
>
> Integer hints:
>
> function foo(int $a) {
>     var_dump($a);
> }
> foo(1); // int(1)
> foo("1"); // int(1)
> foo(1.0); // int(1)
> foo("1a"); // `E_RECOVERABLE_ERROR` 
> foo("a"); // `E_RECOVERABLE_ERROR` 
> foo(999999999999999999999999999999999999); //
> `E_RECOVERABLE_ERROR` (since it's not exactly representable by an int)
> foo(1.5); // `E_RECOVERABLE_ERROR` 
>
> Float hints:
>
> function foo(float $a) {
>     var_dump($a);
> }
> foo(1); // float(1)
> foo("1"); // float(1)
> foo(1.0); // float(1)
> foo("1a"); // `E_RECOVERABLE_ERROR` 
> foo("a"); // `E_RECOVERABLE_ERROR` 
> foo(1.5); // float(1.5)
>
> --
> Andrea Faulds
> http://ajf.me/
>
>
>
>
>
> --
>  To unsubscribe,
visit:
> http://www.php.net/unsub.php

---

## #75404 — Andrea Faulds — 2014-07-13T14:33:54+00:00

URL: https://externals.io/message/75383#75404 · In reply to: #75403

> I think this is a big step in the wrong direction to one of the most
> common auto-conversion use cases out there (HTTP input variables).  See my
> note to Nikita...
> 
> This RFC is a huge deal, I suggest we let more people voice their opinion
> in before changing it in each direction :)
> 
> Zeev

Yes, I might have acted a little too quickly. However, I’m not sure “12a” is such a common case. With the strict behaviour, foobar(“ 12”) and foobar(“12”) still work, however foobar(“12 “) unfortunately would not.
--
Andrea Faulds
http://ajf.me/

---

## #75405 — Zeev Suraski — 2014-07-13T14:41:41+00:00

URL: https://externals.io/message/75383#75405 · In reply to: #75404

> -----Original Message-----
> From: Andrea Faulds [mailto:ajf@ajf.me]
> Sent: Sunday, July 13, 2014 5:34 PM
> To: Zeev Suraski
> Cc: Nikita Popov; PHP internals
> Subject: Re: [PHP-DEV] [RFC] Scalar Type Hinting With Casts (re-opening)
>
>
> 
>
> > […]
>
> Yes, I might have acted a little too quickly. However, I'm not sure
"12a" is such
> a common case. With the strict behaviour, foobar(" 12") and foobar("12")
still
> work, however foobar("12 ") unfortunately would not.

I don't think it's a common intentional case, but when writing code
defensively - you need to be prepared for whatever someone might through
at you...  Say I have a form that accepts 'age', and I expect users to
type in their age.  As one that develops the backend, it's great if I can
simply stick an 'int' in the function signature that deals with this
$_GET['age'], and know that whatever the user typed in - it would turn it
to the most sane integer value.  In other words, if someone types in '12a'
(by mistake or intentionally), I think it's a very sane behavior to just
treat it as 12, as opposed to forcing me (the developer) to write error
handling code with a try/catch block, and a fairly hairy try/catch block
too.  Your example of "12 " (that I didn't even think about before) is an
even a more likely scenario, but I think there's no strong reason not to
allow both.

Zeev

---

## #75406 — Andrea Faulds — 2014-07-13T14:56:46+00:00

URL: https://externals.io/message/75383#75406 · In reply to: #75405

> I don't think it's a common intentional case, but when writing code
> defensively - you need to be prepared for whatever someone might through
> at you...  Say I have a form that accepts 'age', and I expect users to
> type in their age.  As one that develops the backend, it's great if I can
> simply stick an 'int' in the function signature that deals with this
> $_GET['age'], and know that whatever the user typed in - it would turn it
> to the most sane integer value.  In other words, if someone types in '12a'
> (by mistake or intentionally), I think it's a very sane behavior to just
> treat it as 12, as opposed to forcing me (the developer) to write error
> handling code with a try/catch block, and a fairly hairy try/catch block
> too.  Your example of "12 " (that I didn't even think about before) is an
> even a more likely scenario, but I think there's no strong reason not to
> allow both.

I can see what you’re getting at, but then I also think allowing “12a” and the like could be a source of bugs. In this particular case, I’d probably explicitly cast the age myself before doing anything with it.

Forbidding “12a” is closer to the other type hints, which are strict, but is also further away from zpp. I’m a big conflicted.

For now, I’ll leave it as E_RECOVERABLE_ERROR. While user input might be problematic, it can just be filtered.

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

---

## #75407 — Jocelyn Fournier — 2014-07-13T14:59:48+00:00

URL: https://externals.io/message/75383#75407 · In reply to: #75405

Le 13/07/2014 16:41, Zeev Suraski a écrit :
> > […]
> "12a" is such
> > […]
> still
> > […]
>
> I don't think it's a common intentional case, but when writing code
> defensively - you need to be prepared for whatever someone might through
> at you...  Say I have a form that accepts 'age', and I expect users to
> type in their age.  As one that develops the backend, it's great if I can
> simply stick an 'int' in the function signature that deals with this
> $_GET['age'], and know that whatever the user typed in - it would turn it
> to the most sane integer value.  In other words, if someone types in '12a'
> (by mistake or intentionally), I think it's a very sane behavior to just
> treat it as 12, as opposed to forcing me (the developer) to write error
> handling code with a try/catch block, and a fairly hairy try/catch block
> too.  Your example of "12 " (that I didn't even think about before) is an
> even a more likely scenario, but I think there's no strong reason not to
> allow both.

 From my point of view, if the type annotations are doing implicit cast 
(with or without E_NOTICE/E_STRICT warning), they should behave exactly 
the same than an explicit cast. If it behaves differently, I'll be 
really difficult for a developer to guess what will be the PHP behaviour 
with this new syntax.


   Jocelyn

---

## #75408 — me@rouvenwessling.de — 2014-07-13T15:00:30+00:00

URL: https://externals.io/message/75383#75408 · In reply to: #75383

First of all thanks for this proposal. In general I’m hugely in favour of this approach.

One thing however seems like a rather bad idea, and that is exposing the type of resource in this way. Resources are not compatible between each other, making such a hint not very useable. If people start adding this hint to their methods it will also make it much harder to change resources into objects (like it has been done for gmp and I have a pull request for hash)

Best regards
Rouven

---

## #75409 — Zeev Suraski — 2014-07-13T15:01:14+00:00

URL: https://externals.io/message/75383#75409 · In reply to: #75407

>  From my point of view, if the type annotations are doing implicit cast
> (with or
> without E_NOTICE/E_STRICT warning), they should behave exactly the same
> than an explicit cast. If it behaves differently, I'll be really difficult
> for a
> developer to guess what will be the PHP behaviour with this new syntax.

Coming to think of it, this is probably the cleanest and most productive
approach.  +1.

Zeev

---

## #75410 — Andrea Faulds — 2014-07-13T15:01:59+00:00

URL: https://externals.io/message/75383#75410 · In reply to: #75407

> From my point of view, if the type annotations are doing implicit cast (with or without E_NOTICE/E_STRICT warning), they should behave exactly the same than an explicit cast. If it behaves differently, I'll be really difficult for a developer to guess what will be the PHP behaviour with this new syntax.

Well, they do. The results of implicit scalar type hint casts are, so far as I know, the same as explicit casts, but some cases lead to errors which don’t in an explicit casts.

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

---

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