FAQ

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

Andrea Faulds
Jul 13, 2014 at 1:57 am
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/
reply

Search Discussions

247 responses

  • Stas Malyshev at Jul 13, 2014 at 5:22 am
    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/
  • Lester Caine at Jul 13, 2014 at 8:16 am

    On 13/07/14 06:22, Stas Malyshev wrote:
    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
  • Philip Sturgeon at Jul 13, 2014 at 10:17 am

    On Sun, Jul 13, 2014 at 9:16 AM, Lester Caine wrote:
    On 13/07/14 06:22, Stas Malyshev wrote:
    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

    --
    PHP Internals - PHP Runtime Development Mailing List
    To unsubscribe, visit: http://www.php.net/unsub.php
    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.
  • Alain Williams at Jul 13, 2014 at 10:18 am

    On Sun, Jul 13, 2014 at 09:16:33AM +0100, Lester Caine wrote:
    On 13/07/14 06:22, Stas Malyshev wrote:
    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?
    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>
  • Zeev Suraski at Jul 13, 2014 at 11:35 am

    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.
  • Andrea Faulds at Jul 13, 2014 at 11:48 am

    On 13 Jul 2014, at 12:35, Zeev Suraski wrote:

    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/
  • Alain Williams at Jul 13, 2014 at 1:20 pm

    On Sun, Jul 13, 2014 at 02:35:43PM +0300, Zeev Suraski wrote:

    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>
  • Zeev Suraski at Jul 13, 2014 at 2:22 pm

    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
  • Ferenc Kovacs at Jul 14, 2014 at 12:19 pm

    On Sun, Jul 13, 2014 at 12:18 PM, Alain Williams wrote:
    On Sun, Jul 13, 2014 at 09:16:33AM +0100, Lester Caine wrote:
    On 13/07/14 06:22, Stas Malyshev wrote:
    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?
    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 ?
    I think it would be better to reuse declare() instead of reusing var.
    What error level would it emit though?
    I anything below E_RECOVERABLE_ERROR, then it doesn't do anything, but
    prints a line to the error log(and or displays it), which we already do,
    because using an undefined variable will emit an E_NOTICE
    I think it is a good thing if we make it easier to spot programming errors
    and bail out early instead of trying to guess the developer's intention,
    but I don't think that adding more fatal errors or
    E_RECOVERABLE_ERRORs(which will be fatal if there is no userland error
    handler defined which explicitly allows to continue the execution).

    --
    Ferenc Kovács
    @Tyr43l - http://tyrael.hu
  • Alain Williams at Jul 14, 2014 at 12:36 pm

    On Mon, Jul 14, 2014 at 02:19:15PM +0200, Ferenc Kovacs wrote:

    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 think it would be better to reuse declare() instead of reusing var.
    As a matter of curiosity, why ?

    The nice thing about 'var' is that it is the syntax used by other languages, eg
    Javascript.
    What error level would it emit though?
    I anything below E_RECOVERABLE_ERROR, then it doesn't do anything, but
    prints a line to the error log(and or displays it), which we already do,
    because using an undefined variable will emit an E_NOTICE
    I think it is a good thing if we make it easier to spot programming errors
    and bail out early instead of trying to guess the developer's intention,
    but I don't think that adding more fatal errors or
    E_RECOVERABLE_ERRORs(which will be fatal if there is no userland error
    handler defined which explicitly allows to continue the execution).
    This sort of error should be picked up the first time that the script is
    compiled, it does not need to be executed (other than conditional includes).
    This means that these errors will be picked up very quickly.

    --
    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>
  • Ferenc Kovacs at Jul 14, 2014 at 12:47 pm

    On Mon, Jul 14, 2014 at 2:35 PM, Alain Williams wrote:
    On Mon, Jul 14, 2014 at 02:19:15PM +0200, Ferenc Kovacs wrote:

    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 think it would be better to reuse declare() instead of reusing var.
    As a matter of curiosity, why ?

    The nice thing about 'var' is that it is the syntax used by other
    languages, eg
    Javascript.
    in javascript var itself only defines the variable scope/context.
    what you really proposing here is "strict" mode (use strict in javascript),
    and for that declare would be suitable, as that is the current method of
    passing information for the compiler about a file or a codeblock.

    What error level would it emit though?
    I anything below E_RECOVERABLE_ERROR, then it doesn't do anything, but
    prints a line to the error log(and or displays it), which we already do,
    because using an undefined variable will emit an E_NOTICE
    I think it is a good thing if we make it easier to spot programming errors
    and bail out early instead of trying to guess the developer's intention,
    but I don't think that adding more fatal errors or
    E_RECOVERABLE_ERRORs(which will be fatal if there is no userland error
    handler defined which explicitly allows to continue the execution).
    This sort of error should be picked up the first time that the script is
    compiled, it does not need to be executed (other than conditional
    includes).
    This means that these errors will be picked up very quickly.
    that's true, but you didn't really answered my question about the error
    level.

    --
    Ferenc Kovács
    @Tyr43l - http://tyrael.hu
  • Rowan Collins at Jul 14, 2014 at 12:47 pm

    Alain Williams wrote (on 14/07/2014):
    This sort of error should be picked up the first time that the script is
    compiled, it does not need to be executed (other than conditional includes).
    This means that these errors will be picked up very quickly.
    So, it doesn't need to be executed ... except when it does (I can think
    of a few other cases where it's non-trivial to write a compile-time check).

    There are plenty of static analysis tools which will pick up this kind
    of thing, but if you want a language with strict compile-time checks,
    use Hack, which eliminates certain dynamic PHP features in order to make
    stronger guarantees.

    Regards,
    --
    Rowan Collins
    [IMSoP]
  • Andrea Faulds at Jul 13, 2014 at 10:59 am

    On 13 Jul 2014, at 06:22, Stas Malyshev wrote:

    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/
  • Rowan Collins at Jul 13, 2014 at 3:36 pm

    On 13/07/2014 06:22, Stas Malyshev wrote:
    I have one request: could we please stop calling it "hinting"?
    I've always thought the current "type hinting" should be called "type
    assertion", since passing the wrong data type is detected only at
    runtime, and causes an error in much the same way as if you wrote
    assert($param instanceof HintedClass).

    What this RFC proposes is more like "type validation" - detecting that
    the given input can be safely coerced to the given type, and performing
    the coercion in the process. As Andrea points, out, it's similar to what
    Nikita called[1] "strict weak type hinting", but with the added step of
    performing the cast, which is really just a convenience, since if you've
    asked for a value to be validated as an int, you're presumably about to
    use it as one.

    [1]
    http://nikic.github.io/2012/03/06/Scalar-type-hinting-is-harder-than-you-think.html

    --
    Rowan Collins
    [IMSoP]
  • Sebastian Bergmann at Jul 20, 2014 at 7:33 am

    Am 13.07.2014 07:22, schrieb Stas Malyshev:
    I think it was a mistake to introduce this term from the start and
    we should stop propagating it.
      What would be a better term? Optional strict typing in function and
      method signatures?
  • Andrea Faulds at Jul 20, 2014 at 12:42 pm

    On 20 Jul 2014, at 08:33, Sebastian Bergmann wrote:

    Am 13.07.2014 07:22, schrieb Stas Malyshev:
    I think it was a mistake to introduce this term from the start and
    we should stop propagating it.
    What would be a better term? Optional strict typing in function and
    method signatures?
    This proposal’s scalar type hints (except for booleans) can’t really be called “strict”. Perhaps “firm typing”? (It’s not weak, but it’s not quite strong either)
    --
    Andrea Faulds
    http://ajf.me/
  • Ferenc Kovacs at Jul 20, 2014 at 2:54 pm
    2014.07.20. 14:43, "Andrea Faulds" <aj...@...me> ezt írta:
    On 20 Jul 2014, at 08:33, Sebastian Bergmann wrote:

    Am 13.07.2014 07:22, schrieb Stas Malyshev:
    I think it was a mistake to introduce this term from the start and
    we should stop propagating it.
    What would be a better term? Optional strict typing in function and
    method signatures?
    This proposal’s scalar type hints (except for booleans) can’t really be
    called “strict”. Perhaps “firm typing”? (It’s not weak, but it’s not quite
    strong either)

    Stas and Sebastian are talking about the unfortunate naming of the current
    (non-scalar) typehints.
  • Andrea Faulds at Jul 20, 2014 at 2:56 pm

    On 20 Jul 2014, at 15:54, Ferenc Kovacs wrote:

    This proposal’s scalar type hints (except for booleans) can’t really be called “strict”. Perhaps “firm typing”? (It’s not weak, but it’s not quite strong either)
    Stas and Sebastian are talking about the unfortunate naming of the current (non-scalar) type hints.
    Oh, of course. Perhaps we could say that the non-scalar type hints are “optional strict typing” and the scalar type hints are “optional firm typing”?

    --
    Andrea Faulds
    http://ajf.me/
  • Stas Malyshev at Jul 20, 2014 at 6:29 pm
    Hi!
    What would be a better term? Optional strict typing in function and
    method signatures?
    Parameter typing, or typed parameters if you will. One of the options,
    of course, there could be many others.

    --
    Stanislav Malyshev, Software Architect
    SugarCRM: http://www.sugarcrm.com/
  • Robert Williams at Jul 23, 2014 at 6:21 pm

    On Jul 14, 2014, at 10:13, Andrea Faulds wrote:
    We are using hack’s syntax (int, float, bool, string, no integer/double/boolean aliases).
    On 20 Jul 2014, at 14:11, Andrea Faulds wrote:
    The patch actually warns you if you try to do this now:

    function foo(double $foo) {}
    foo(1.0);

    If you use one of the non-existent aliases (double), and pass the type that alias is supposed to hint for (a float), the error message notes you might be looking for the actual type hint (`float`).

    It seems odd to me to not support the aliases. Since I can do this:

        $foo = (integer)$bar;

    I would expect to be able to do this:

        function foo(integer $param) {}

    Also, do int, float, and numeric accept numbers in octal, hex, scientific notation, etc.? I don’t believe there are any examples in the RFC that intentionally or accidentally show what happens with, say, 0x2f as a value.


    --
    Bob Williams
    SVP, Software Development
    Newtek Business Services, Inc.
    “The Small Business Authority”
    http://www.thesba.com/

    Notice: This communication, including attachments, may contain information that is confidential. It constitutes non-public information intended to be conveyed only to the designated recipient(s). If the reader or recipient of this communication is not the intended recipient, an employee or agent of the intended recipient who is responsible for delivering it to the intended recipient, or if you believe that you have received this communication in error, please notify the sender immediately by return e-mail and promptly delete this e-mail, including attachments without reading or saving them in any manner. The unauthorized use, dissemination, distribution, or reproduction of this e-mail, including attachments, is prohibited and may be unlawful. If you have received this email in error, please notify us immediately by e-mail or telephone and delete the e-mail and the attachments (if any).
  • Andrea Faulds at Jul 23, 2014 at 6:37 pm

    On 23 Jul 2014, at 19:21, Robert Williams wrote:

    It seems odd to me to not support the aliases. Since I can do this:

    $foo = (integer)$bar;

    I would expect to be able to do this:

    function foo(integer $param) {}
    Aliases mean inconsistency. We shouldn’t unnecessarily have multiple names for the same thing, just one. Also, for every alias we support, another reserved word is added. Hence we only allow one set of names. This is also Facebook’s approach with Hack, which removes the aliases entirely for type casting. I might propose we deprecate/remove the aliases in a future RFC.
    Also, do int, float, and numeric accept numbers in octal, hex, scientific notation, etc.? I don’t believe there are any examples in the RFC that intentionally or accidentally show what happens with, say, 0x2f as a value.
    Ooh, you’ve caught me out there. The patch as it stands would permit such non-decimal numbers, which isn’t what it should do as convert_to_long_base_safe should actually permit only the specified base.

    So, yes it does permit non-decimal numbers, but it’s a bug I need to fix.

    --
    Andrea Faulds
    http://ajf.me/
  • Robert Williams at Jul 23, 2014 at 9:17 pm

    On Jul 23, 2014, at 11:37, Andrea Faulds wrote:

    Aliases mean inconsistency. We shouldn’t unnecessarily have multiple names for the same thing, just one. Also, for every alias we support, another reserved word is added. Hence we only allow one set of names. This is also Facebook’s approach with Hack, which removes the aliases entirely for type casting. I might propose we deprecate/remove the aliases in a future RFC.
    I agree the aliases, by definition, represent inconsistency. However, that inconsistency is already in the language, and those keywords already exist. By not supporting the aliases in new functionality that’s so closely related, the inconsistency is itself inconsistent.

    Although I don’t have voting rights, I would completely support a separate RFC to remove the aliases in PHP 6/7. But in the mean time, as long as they’re still in the language, I think they need to be fully supported anywhere their “real” counterparts can be used. Hack didn’t just remove them in some cases, it removed them across the board. And I think that’s the right approach: they’re supported across the board until they’re no longer supported, and then they’re not supported anywhere.
    So, yes it does permit non-decimal numbers, but it’s a bug I need to fix.
    I’m not sure I follow. If I have function foo(int $bar) {}, what happens in these cases:

        foo(0x2f);
        foo(‘0x2f’);

    Related, is “numeric" basically the union of “int” and “float” (as appears to be the case from the chart in the RFC), or is it something more along the lines of is_numeric()? There could be consistency issues lurking here, too.


    Regards,
    Bob

    --
    Robert E. Williams, Jr.
    Senior Vice President of Software Development
    Newtek Businesss Services, Inc. -- The Small Business Authority
    https://www.newtekreferrals.com/rewjr
    http://www.thesba.com/


    Notice: This communication, including attachments, may contain information that is confidential. It constitutes non-public information intended to be conveyed only to the designated recipient(s). If the reader or recipient of this communication is not the intended recipient, an employee or agent of the intended recipient who is responsible for delivering it to the intended recipient, or if you believe that you have received this communication in error, please notify the sender immediately by return e-mail and promptly delete this e-mail, including attachments without reading or saving them in any manner. The unauthorized use, dissemination, distribution, or reproduction of this e-mail, including attachments, is prohibited and may be unlawful. If you have received this email in error, please notify us immediately by e-mail or telephone and delete the e-mail and the attachments (if any).
  • Andrea Faulds at Jul 23, 2014 at 9:29 pm

    On 23 Jul 2014, at 22:17, Robert Williams wrote:

    Although I don’t have voting rights, I would completely support a separate RFC to remove the aliases in PHP 6/7. But in the mean time, as long as they’re still in the language, I think they need to be fully supported anywhere their “real” counterparts can be used. Hack didn’t just remove them in some cases, it removed them across the board. And I think that’s the right approach: they’re supported across the board until they’re no longer supported, and then they’re not supported anywhere.
    Right, but none of the aliases are reserved words already and I really don’t want to introduce more reserved words than I have to, otherwise it’s going to upset a lot of people.
    --
    Andrea Faulds
    http://ajf.me/
  • Andrea Faulds at Jul 24, 2014 at 11:48 pm

    On 23 Jul 2014, at 19:37, Andrea Faulds wrote:

    On 23 Jul 2014, at 19:21, Robert Williams wrote:

    Also, do int, float, and numeric accept numbers in octal, hex, scientific notation, etc.? I don’t believe there are any examples in the RFC that intentionally or accidentally show what happens with, say, 0x2f as a value.
    Ooh, you’ve caught me out there. The patch as it stands would permit such non-decimal numbers, which isn’t what it should do as convert_to_long_base_safe should actually permit only the specified base.

    So, yes it does permit non-decimal numbers, but it’s a bug I need to fix.
    Said bug has been fixed in the proposed patch now. “0xa” is no longer valid for int, float or numeric. It never should’ve been valid, but the implementation of convert_to_(long_base|double|numeric)_safe was incorrect.

    --
    Andrea Faulds
    http://ajf.me/
  • Nikita Popov at Jul 13, 2014 at 12:09 pm

    On Sun, Jul 13, 2014 at 3:57 AM, Andrea Faulds wrote:

    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
  • Jocelyn Fournier at Jul 13, 2014 at 12:50 pm
    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 :
    On Sun, Jul 13, 2014 at 3:57 AM, Andrea Faulds wrote:

    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
  • Andrea Faulds at Jul 13, 2014 at 12:56 pm

    On 13 Jul 2014, at 13:50, Jocelyn Fournier wrote:

    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/
  • Jocelyn Fournier at Jul 13, 2014 at 1:13 pm
    Hi,

    Le 13/07/2014 14:56, Andrea Faulds a écrit :
    On 13 Jul 2014, at 13:50, Jocelyn Fournier wrote:

    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.
    Actually displaying a warning in E_STRICT but still doing the implicit
    cast would not change the function signature.
    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.
    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.


    Thanks,
        Jocelyn
  • Andrea Faulds at Jul 13, 2014 at 1:18 pm

    On 13 Jul 2014, at 14:13, Jocelyn Fournier wrote:

    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/
  • Jocelyn Fournier at Jul 13, 2014 at 1:54 pm
    Le 13/07/2014 15:17, Andrea Faulds a écrit :
    On 13 Jul 2014, at 14:13, Jocelyn Fournier wrote:

    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.
    Ok, in this case I would suggest always displaying a warning in E_STRICT
    since it's the whole purpose of the strict mode :)
    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.
    If I'm not able to use type annotation because I *really* want to
    enforce the calling function variable type, I'm potentially missing some
    optimisations. (but with warning in strict mode, all is fine)

        Jocelyn
  • Andrea Faulds at Jul 13, 2014 at 1:58 pm

    On 13 Jul 2014, at 14:54, Jocelyn Fournier wrote:

    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/
  • Jocelyn Fournier at Jul 13, 2014 at 2:25 pm
    Le 13/07/2014 15:58, Andrea Faulds a écrit :
    On 13 Jul 2014, at 14:54, Jocelyn Fournier wrote:

    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.
    BTW, is there a doc somewhere describing what E_NOTICE and E_STRICT
    really stand for ? (if not, that would be great)
    I can see indeed in
    http://php.net//manual/en/function.error-reporting.php "Most of E_STRICT
    errors are evaluated at the compile time", but "most" means there are
    already exceptions ? :)

    That said, either E_NOTICE or E_STRICT would be fine for me.


        Jocelyn
  • Andrea Faulds at Jul 13, 2014 at 2:20 pm

    On 13 Jul 2014, at 13:09, Nikita Popov wrote:

    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/
  • Zeev Suraski at Jul 13, 2014 at 2:31 pm
    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
    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)

    On 13 Jul 2014, at 13:09, Nikita Popov wrote:

    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/





    --
    PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit:
    http://www.php.net/unsub.php
  • Andrea Faulds at Jul 13, 2014 at 2:34 pm

    On 13 Jul 2014, at 15:31, Zeev Suraski wrote:

    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/
  • Zeev Suraski at Jul 13, 2014 at 2:41 pm

    -----Original Message-----
    From: Andrea Faulds
    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)

    On 13 Jul 2014, at 15:31, Zeev Suraski wrote:

    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.
    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
  • Andrea Faulds at Jul 13, 2014 at 2:56 pm

    On 13 Jul 2014, at 15:41, Zeev Suraski wrote:

    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/
  • Jocelyn Fournier at Jul 13, 2014 at 2:59 pm

    Le 13/07/2014 16:41, Zeev Suraski a écrit :
    -----Original Message-----
    From: Andrea Faulds
    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)

    On 13 Jul 2014, at 15:31, Zeev Suraski wrote:

    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.
    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
  • Zeev Suraski at Jul 13, 2014 at 3:01 pm

    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
  • Andrea Faulds at Jul 13, 2014 at 3:19 pm

    On 13 Jul 2014, at 16:01, Zeev Suraski wrote:

    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.
    If we interpret that to mean just casting everything with no error cases, but E_NOTICE on some, then it is one of the three main proposals suggested for scalar type hinting:

    1. Casting type hints
    2. Strict type hints
    3. Scalar type hinting with casts

    (There are others, but I won’t talk about them)

    I’m not of the opinion that the first option, where we just cast and never error, is ideal. It does ensure the values are of the correct type when they get to you, so it keeps PHP’s type juggling, but it is unlikely to catch bugs where the wrong value has been passed.

    The second option, while appealing to some, goes completely against PHP’s type juggling. You’d have to manually cast everything yourself. As I understand it, this is essentially what Hack does, but PHP is not Hack and I don’t really think this is a good idea.

    A fourth option would be to allow both by using different syntaxes for casting and strict, but I don’t think we should add two different ways because we can’t agree; we should do it just one way.

    The final option, which this RFC proposes, is something of a compromise between the two proposals. I think it’s sufficiently strict to prevent bugs, and the parameter will be the right type, but it does not stop type-juggling.

    Nikita wrote about the subject of the different approaches here in 2012: http://nikic.github.io/2012/03/06/Scalar-type-hinting-is-harder-than-you-think.html

    However, I don’t propose “strict weak” typing, I propose this RFC.

    --
    Andrea Faulds
    http://ajf.me/
  • Zeev Suraski at Jul 13, 2014 at 3:45 pm

    -----Original Message-----
    From: Andrea Faulds
    Sent: Sunday, July 13, 2014 6:19 PM
    To: Zeev Suraski
    Cc: Jocelyn Fournier; PHP internals
    Subject: Re: [PHP-DEV] [RFC] Scalar Type Hinting With Casts (re-opening)

    1. Casting type hints
    2. Strict type hints
    3. Scalar type hinting with casts

    (There are others, but I won't talk about them)

    I'm not of the opinion that the first option, where we just cast and never
    error, is ideal. It does ensure the values are of the correct type when they get
    to you, so it keeps PHP's type juggling, but it is unlikely to catch
    bugs where
    the wrong value has been passed.
    Let's stop for a moment right here.
    If we emit notices, or even new E_CAST, do we not get the exact same
    ability to catch errors you'd get from E_RECOVERABLE_ERROR?
    Even reading Nikita's piece, he's saying he dislikes that option for
    'obvious reasons', but I see nothing obviously wrong with this approach.
    In fact, it gives you the full power of ensuring the correct types in the
    'inner code', allows you to catch 'bad conversions' if you wish to (many
    don't, but I agree some and perhaps many would), and allows you to use
    this feature in the most widespread way possible while minimizing the
    amount of code you need to write in order to use it (no inflation in
    necessary try/catch blocks). Unlike what's suggested in that piece, it's
    not equivalent at all to docblocks, as it is in fact enforced, and as you
    said, has the benefit of being able to write the 'inner code' without
    worrying about the input types.

      Whether we go for option #1 or #3 doesn't change the amount of bugs you
    can find *if you wish to, unless I'm missing something. Option #3 forces
    you to explicitly deal with 'error' situations (which may or may not be
    errors), while option #1 leaves it up to the developer whether he wants
    to write 'E_CAST clean' code or not, similarly to E_STRICT (assuming we
    introduce E_CAST, we can choose an existing error level too).

    Zeev
  • Rowan Collins at Jul 13, 2014 at 4:09 pm

    On 13/07/2014 16:45, Zeev Suraski wrote:
    Even reading Nikita's piece, he's saying he dislikes that option for
    'obvious reasons', but I see nothing obviously wrong with this approach.
    [...] Unlike what's suggested in that piece, it's
    not equivalent at all to docblocks, as it is in fact enforced, and as you
    said, has the benefit of being able to write the 'inner code' without
    worrying about the input types.
    I think you're muddling two sections of Nikita's article [1]. The option
    which is dismissed "for obvious reasons" is "unenforced type hinting" -
    keywords which do absolutely nothing other than give a literal hint to
    non-critical tools like documentation and reflection.

    The next section is about "casting weak type hinting", which is
    described as "one of the more interesting proposals". It certainly has
    merit, although in my opinion it's less powerful than the other options
    in what it adds to the language, as the equivalent userland boilerplate
    is really minimal (e.g. $foo = (int)$foo).

    As I've mentioned elsewhere, and indeed was mentioned in Anthony's
    proposal at the time [2], the addition of warnings on lossy casts is a
    completely separate issue to the ability to sugar those casts into a
    function signature.

    Now, what is being proposed here is effectively "casting strict type
    hinting", a variant of what Nikita called "strict weak type hinting",
    with the additional step of actually applying the lossless cast, rather
    than just asserting that it's possible. This actually provides a lot of
    functionality which is fiddly to implement in userland, and I can't see
    a lot of uses for asserting that a cast would be non-lossy, if you're
    not about to perform that cast (which is what "strict weak type hinting"
    allows).

    [1]
    http://nikic.github.io/2012/03/06/Scalar-type-hinting-is-harder-than-you-think.html
    [2] http://blog.ircmaxell.com/2012/03/parameter-type-casting-in-php.html

    --
    Rowan Collins
    [IMSoP]
  • Zeev Suraski at Jul 13, 2014 at 4:28 pm

    -----Original Message-----
    From: Rowan Collins
    Sent: Sunday, July 13, 2014 7:09 PM
    To: int...@...net
    Subject: Re: [PHP-DEV] [RFC] Scalar Type Hinting With Casts (re-opening)
    On 13/07/2014 16:45, Zeev Suraski wrote:
    Even reading Nikita's piece, he's saying he dislikes that option for
    'obvious reasons', but I see nothing obviously wrong with this approach.
    [...] Unlike what's suggested in that piece, it's not equivalent at
    all to docblocks, as it is in fact enforced, and as you said, has the
    benefit of being able to write the 'inner code' without worrying about
    the input types.
    I think you're muddling two sections of Nikita's article [1]. The option
    which is
    dismissed "for obvious reasons" is "unenforced type hinting" - keywords
    which do absolutely nothing other than give a literal hint to non-critical
    tools
    like documentation and reflection.
    You're absolutely right. My bad. BTW, auto-converting type hints were
    proposed by Lukas and me back in 2010, even though I see them attributed to
    Anthony in 2012 :)
    The next section is about "casting weak type hinting", which is described
    as
    "one of the more interesting proposals". It certainly has merit, although
    in my
    opinion it's less powerful than the other options in what it adds to the
    language, as the equivalent userland boilerplate is really minimal (e.g.
    $foo =
    (int)$foo).
    That's not a bad thing in my book - another way to describe it is that it's
    consistent with the rest of the language and doesn't require developers to
    learn another new set of 'similar, but different' semantics.

    In terms of value that it does bring to the table, it gives you a standard
    way to do something that's very common in a shorter way and increases
    quality of APIs (it's much more likely people will use this to describe
    their APIs than docblocks), and we can use better warning semantics than we
    currently have on conversions (without changing the rules), and it allows
    you to do all that without having to add tons of defensive code (in the
    calling code) that is often unnecessary. Making it easy to implement means
    it'll get used more - and so far I fail to see what we stand to lose (more
    on that below).
    As I've mentioned elsewhere, and indeed was mentioned in Anthony's
    proposal at the time [2], the addition of warnings on lossy casts is a
    completely
    separate issue to the ability to sugar those casts into a function
    signature.
    I don't see why they would be separate, especially if the key reason for
    going for 'option #3' is that it helps find bugs better. Option #1 with the
    added logic of warning about lost data or 'bogus' conversions has all the
    advantages of option #3 but also other advantages.
    Now, what is being proposed here is effectively "casting strict type
    hinting", a
    variant of what Nikita called "strict weak type hinting", with the
    additional step
    of actually applying the lossless cast, rather than just asserting that
    it's
    possible. This actually provides a lot of functionality which is fiddly to
    implement in userland, and I can't see a lot of uses for asserting that a
    cast
    would be non-lossy, if you're not about to perform that cast (which is
    what
    "strict weak type hinting"
    allows).
    Again, option #1 as I see it (and is mostly described in the 2010 RFC
    https://wiki.php.net/rfc/typecheckingstrictandweak) - it's identical in
    terms of rules to those of PHP's casting, but with warnings emitted for lost
    data and 'bogus' conversions. If we introduce this feature in a major
    version, we could also consider change the casting code to emit these same
    warnings so that we get full consistency - but that I think is in fact a
    separate decision.

    Zeev
  • Rowan Collins at Jul 13, 2014 at 5:00 pm

    On 13/07/2014 17:28, Zeev Suraski wrote:
    BTW, auto-converting type hints were
    proposed by Lukas and me back in 2010, even though I see them attributed to
    Anthony in 2012 :)
    Aha, seems like a case of convergent thinking, with the exception that
    Anthony proposed using distinct syntax to represent the casts (the wiki
    isn't rendering properly for me, so apologies if that is also covered in
    your older proposal).

    As I've mentioned elsewhere, having the same syntax mean "assert" for
    scalars but "cast" for non-scalars leads to an ambiguity with arrays,
    for which both actions are available (and current code performs an
    assertion).
    The next section is about "casting weak type hinting", which is described
    as
    "one of the more interesting proposals". It certainly has merit, although
    in my
    opinion it's less powerful than the other options in what it adds to the
    language, as the equivalent userland boilerplate is really minimal (e.g.
    $foo =
    (int)$foo).
    That's not a bad thing in my book - another way to describe it is that it's
    consistent with the rest of the language and doesn't require developers to
    learn another new set of 'similar, but different' semantics.

    In terms of value that it does bring to the table, it gives you a standard
    way to do something that's very common in a shorter way and increases
    quality of APIs (it's much more likely people will use this to describe
    their APIs than docblocks), and we can use better warning semantics than we
    currently have on conversions (without changing the rules), and it allows
    you to do all that without having to add tons of defensive code (in the
    calling code) that is often unnecessary. Making it easy to implement means
    it'll get used more - and so far I fail to see what we stand to lose (more
    on that below).
    I think a lot of this hinges on the next question, of whether the
    warning semantics are inherently tied to this new syntax, or a separate
    issue.

    To me, it makes perfect sense for the following to be equivalent, with
    one just a more expressive way of writing it:

    function casts_as_array($foo) { $foo = (array)$foo; /* ... */ }
    function casts_as_array((array)$foo) { /* ... */ }

    As I've mentioned elsewhere, and indeed was mentioned in Anthony's
    proposal at the time [2], the addition of warnings on lossy casts is a
    completely
    separate issue to the ability to sugar those casts into a function
    signature.
    I don't see why they would be separate, especially if the key reason for
    going for 'option #3' is that it helps find bugs better. Option #1 with the
    added logic of warning about lost data or 'bogus' conversions has all the
    advantages of option #3 but also other advantages.
    Other than isolating the change for backwards compatibility, I don't see
    a big reason to treat them as separate. If the aim is to make the scalar
    type hints "just like an existing cast", then lossy casts should work
    the same way in both places.

    On the other hand, if the aim is to make it easier to detect lossy
    casts, then a way to do that *outside* function signatures is just as
    useful as a way embedded in them.

    In fact, thinking about it, several of these proposals add implicit
    functionality in the function signature which would remain tricky in
    userland code. Current type-hinting does not do this (it can be emulated
    fairly easily with is_array(), is_callable(), and instanceof).

    If we don't want all casts to emit warnings on loss, perhaps a new
    function or keyword request them - e.g. (strict int)$foo, or
    strict_cast($foo, 'int').

    Regards,

    --
    Rowan Collins
    [IMSoP]
  • Larry Garfield at Jul 13, 2014 at 5:56 pm

    On 07/13/2014 11:28 AM, Zeev Suraski wrote:
    Again, option #1 as I see it (and is mostly described in the 2010 RFC
    https://wiki.php.net/rfc/typecheckingstrictandweak) - it's identical in
    terms of rules to those of PHP's casting, but with warnings emitted for lost
    data and 'bogus' conversions. If we introduce this feature in a major
    version, we could also consider change the casting code to emit these same
    warnings so that we get full consistency - but that I think is in fact a
    separate decision.

    Zeev
    I want to call out this point because I think it's key. Remember that
    when an E_* is emitted, if it's not trapped then code execution
    continues. That means we can, and should, think about what the
    resulting value is independently of what if any E_* message is emitted.

    That is:

    function give_int(int $foo) { }
    give_int('123abc');

    The value of $foo should be 123 (int), because that's what casting rules
    say. However, because that's lossy an E_* should get emitted to warn
    the developer "hey, not what I meant!" If the error handler doesn't
    terminate the process, though, then give_array() will continue to
    execute and in that case the value that results from the cast MUST be
    the same as if it were done explicitly.

    We can discuss when the E_* should be emitted separately from what the
    cast result is.

    The one caveat to that is arrays, as someone else noted:

    Current PHP:

    function give_array(array $foo) { var_dump($foo); }
    give_array('abc');
    // Catchable fatal error.

    Whereas if it follows the hint rules, apparently:
    array(1) { [0]=> string(3) "abc" }

    Which as a developer I wouldn't want, since that's likely to break my
    code's assumptions. Array is weird in that we'd be changing from a type
    specifier to a type caster. (ie, less like objects, more like
    primitives.) As long as it's an error of some kind it may be OK, but
    perhaps we want to leave array as is (strict behavior) rather than
    changing it to the primitive logic (cast behavior)?

    --Larry Garfield
  • Andrea Faulds at Jul 13, 2014 at 6:21 pm

    On 13 Jul 2014, at 18:56, Larry Garfield wrote:

    We can discuss when the E_* should be emitted separately from what the cast result is.
    Is there any actual controversy over what the *result* of casts should be. This RFC just has the normal casting result. Is anyone really in disagreement there?
    As long as it's an error of some kind it may be OK, but perhaps we want to leave array as is (strict behavior) rather than changing it to the primitive logic (cast behaviour)?
    I think the discussion about how arrays should be casted too for consistency is a bit silly. What makes sense for non-scalar types (strict hinting) may not work so well for scalar types; casting to array is rarely useful, while casting to the scalar types is readily. Also, frankly, function foobar((int) $a, array $b) is inconsistent and ugly.

    Note too that the non-scalar types, while they can be casted from, can’t always be casted to. You can cast to an object, but only StdClass, and you can’t cast to resource at all.

    I really don’t think there’s anything wrong with having one system for the scalar types and one for the non-scalar types since they’re so different.
    --
    Andrea Faulds
    http://ajf.me/
  • Rowan Collins at Jul 13, 2014 at 7:20 pm

    On 13/07/2014 19:21, Andrea Faulds wrote:
    On 13 Jul 2014, at 18:56, Larry Garfield wrote:

    We can discuss when the E_* should be emitted separately from what the cast result is.
    Is there any actual controversy over what the *result* of casts should be. This RFC just has the normal casting result. Is anyone really in disagreement there?
    Well, I think the behaviour of ' 42' and '42 ' passed as int could be
    worth reviewing.

    As long as it's an error of some kind it may be OK, but perhaps we want to leave array as is (strict behavior) rather than changing it to the primitive logic (cast behaviour)?
    I think the discussion about how arrays should be casted too for consistency is a bit silly. What makes sense for non-scalar types (strict hinting) may not work so well for scalar types; casting to array is rarely useful, while casting to the scalar types is readily.
    I'm not sure I agree with this. I regularly use foreach( (array)$foo as
    $bar ) for instance - it has the convenient behaviour of looping zero
    times for null, once for a scalar, and leaving an existing array alone.

    Objects are definitely a different case, because they have a lot of
    unique behaviour (class hierarchies, additional reference indirection,
    etc). It sometimes makes sense to bundle arrays with objects, in terms
    of "scalar vs non-scalar", but other times it makes more sense to think
    of "simple types (including arrays) vs objects". A mutable, unbounded
    string isn't really "scalar" in the same way as a fixed-size integer,
    anyway.

    Also, frankly, function foobar((int) $a, array $b) is inconsistent and ugly.
    Ugly, maybe, but less inconsistent than having function foobar(int $a,
    array $b) { } foobar('a', 'b'); perform a cast to 0 on $a but a fatal
    error for $b.

    If there were a mixed syntax, you'd probably be using the cast type for
    both anyway: function foobar((int) $a, (array) $b)

    Still, the mixed validate-and-cast approach of this RFC gets around this
    nicely, because there is no "safe cast" to an array available, so no
    case that needs addressing. This doesn't really have to do with it being
    "non-scalar" per se, just that there's no "natural" type-juggling like
    there is for '123' => int or '1.5' => float.

    --
    Rowan Collins
    [IMSoP]
  • Arvids Godjuks at Jul 14, 2014 at 10:10 am
    Hello!

    As a user land developer I do think that over thinking this is going to end
    up in disaster.
    We already have quite good implementation for the array and object hints,
    they do their job and do it good. No need to change those at all - leave
    them as is - no need to add magic with casts and all that. Function/method
    requires an array? Make casts explicitly and pass it an array and not an
    integer.

    Primitive type hints are a little different - they are easily cast into
    each other for the most part. The only edge case is when we loose data. In
    this case we need a E_STRICT or something like that (I would vote for
    E_TYPEHINT_CAST - because you will be able to disable only typehint
    warnings/errors without disabling E_STRICT), so we can collect these errors
    and fix our code by adding checks/casts/whatever. But this automatic
    casting should work only between string, integer, float, bool and null
    types and only between these. No automatic casting of these 5 to arrays or
    objects.

    PHP does not need a type hinting system forces you to first make a
    prototype without any type hints because you get catchable errors - you can
    handle them, but you can't actually just continue right where the error
    occurred. You just need to get a warning, that you can disable via
    error_reporting, and just make your prototype with all the type hints you
    need and deal with the cast warnings in the type hints later on.

    P.S. And on that "var integer $variable" in methods/functions. People, when
    you have internal functions returning null|array, bool|array and so on -
    this is pointless.
  • Alain Williams at Jul 14, 2014 at 11:19 am

    On Mon, Jul 14, 2014 at 01:09:42PM +0300, Arvids Godjuks wrote:

    PHP does not need a type hinting system forces you to first make a
    No one is 'forcing' anything. You use it where it is appropriate; that does not
    mean everywhere - there are plenty of places where I would not want to use it.
    P.S. And on that "var integer $variable" in methods/functions. People, when
    you have internal functions returning null|array, bool|array and so on -
    this is pointless.
    In that case you would declare "var $variable" to receive the value from such a function.

    The point of the use of "var" is to ensure that variables are declared before use.
    There is a whole set of errors that can be eliminated by this -- typeos where
    you assign to the 'wrong' variable.

         http://stackoverflow.com/questions/8023959/why-use-strict-and-warnings

    "var integer $variable" has a use where do you know they type, eg you got it
    from the typed function arguments.

    As with all of this: if you don't find it then don't use it, leave it for those
    who do understand the benefits.

    --
    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>
  • Arvids Godjuks at Jul 14, 2014 at 1:32 pm

    2014-07-14 14:19 GMT+03:00 Alain Williams <add...@...uk>:
    On Mon, Jul 14, 2014 at 01:09:42PM +0300, Arvids Godjuks wrote:

    PHP does not need a type hinting system forces you to first make a
    No one is 'forcing' anything. You use it where it is appropriate; that
    does not
    mean everywhere - there are plenty of places where I would not want to use
    it.
    The trend I see in the messages is that people tend to drift to a
    restrictive model of type hints - you pass the wrong type and get an
    E_RECOVERABLE_ERROR, or add the warning to E_STRICT level (now I don't get
    strict warnings at all) or something else comes up.
    People forget the KISS, people forget that someone actually has to
    implement all that and it's not easy by far. All that additional stuff is
    going to take a lot of development time, will slow down the engine
    (especially if we do array/object casts - what if someone passes a big
    object collection to an array parameter or vice-verse?).
    It just feels wrong and unnecessary. If you feel PHP does not provide you
    with enough strictness - switch the language.

    P.S. And on that "var integer $variable" in methods/functions. People, when
    you have internal functions returning null|array, bool|array and so on -
    this is pointless.
    In that case you would declare "var $variable" to receive the value from
    such a function.

    The point of the use of "var" is to ensure that variables are declared
    before use.
    There is a whole set of errors that can be eliminated by this -- typeos
    where
    you assign to the 'wrong' variable.

    http://stackoverflow.com/questions/8023959/why-use-strict-and-warnings

    "var integer $variable" has a use where do you know they type, eg you got
    it
    from the typed function arguments.

    As with all of this: if you don't find it then don't use it, leave it for
    those
    who do understand the benefits.

    And more pointless boilerplate code to write. If I need a variable
    initialized - I just initialize it: $var = 0;
    Any modern IDE and even some editors will show you uninitialized or/and
    unused variables.
    Renaming is for "Refactor -> Rename".

    PHP team has enough on it's plate than writing a static analyzer into the
    code parser, implementing over-complicated RFC's and so on. People on this
    list have to start to think practically. Previous RFC's for the type hints
    didn't got through because of people trying to get all the things into
    them, agreeing to disagree and authors just got fed up and probably (I
    guess here) when realizing into how big and complicated a peace of work the
    RFC became just bailed out with "FUA" (I definitely would do exactly that,
    of course never stating that directly in public, just would declare the
    dropping of the RFC - but it would be what I felt internally).


    So my proposal is to go the KISS way and make baby steps, see what fruit it
    will spawn. Do the basic param hints, use leftover time to pick up the
    "Return type hints" RFC. See how it all pans out in the real world and then
    do improvements, if necessary. Basic type hints for scalar types with type
    casting, don't touch array and object type hints, add
    a E_TYPEHINT_CAST_WARNING warning level so you can generate them when data
    loss occurs. And don't change explicit casting. Just to show what I mean:

    function test(int $param) { };

    // $_GET['id'] === '123a'

    test($_GET['id']);
    // Get a E_TYPEHINT_CAST_WARNING

    test((int)$_GET['id'])
    // Everything works like a charm

    The last workflow, when I do an explicit cast, is kind'a what many are used
    to with the PHP casting system. The difference with type hint is that I can
    check where I forgot to make the explicit cast and PHP Engine, in the
    future, can make use of explicit cast being made and optimize the $param
    usage in the function as an integer. This also gives the ability to update
    the code peace by peace and not suffer from tons of warnings/errors that
    are generated by typehint casts that loose data that are disabled only with
    some other type of errors/warnings that I would like to stay enabled (I run
    my code in E_ALL | E_STRICT on production with display_errors = Off -
    anything that get's into logs is being fixed ASAP).

Related Discussions