SitePoint Sponsor

User Tag List

Page 1 of 3 123 LastLast
Results 1 to 25 of 62
  1. #1
    SitePoint Zealot Amenthes's Avatar
    Join Date
    Oct 2006
    Location
    Bucharest, Romania
    Posts
    143
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Looks like we're gonna have typed parameters in PHP

    Hi guys,

    I'm a frequent lurker on the PHP internals mailing list, so a few days ago I witnessed
    the beginning of a "hot" discussion. The issue is about introducing typed parameters
    in PHP. Ilia Alshanetsky brought a third patch (in the past there were other two
    attempts made by other developers) that introduces a new syntax for checking
    types of parameters. It looked like this:

    PHP Code:
    <?php

    function foo(int $astring $b) {}
    Note! There are no types for return values.

    However, people raise the problem of dynamic typing which is one of the key
    features in PHP, and proposed that this feature be accompanied by a way of
    casting arguments right there, in the parameters' body. There where three
    long threads, but a few days ago there was a call for vote for a final patch
    that introduces the following:

    Strict type check
    PHP Code:
    <?php
    /**
     * Whenever the type of $a is not integer, an E_RECOVERABLE_ERROR
     * is issued.
     */
    function foo(int $astring $b) {}
    Weak type check/hint/cast
    PHP Code:
    <?php

    /**
     * This solution uses the existent syntax of type casting. Whenever the
     * argument cannot be casted to the desired type, an E_RECOVERABLE_ERROR with
     * an appropriate message is issued.
     */
    function foo((int) $a, (string) $b) {}
    This new feature was proposed for addition to the language in the current
    PHP 5.3 branch.

    Many people voted for it, but I guess they missed the PHP 5.3 part because,
    after someone said it is against it for PHP 5.3, but agrees for a future version
    like 5.4 or 6, many others changed their minds in the same way.

    Others raised the issue of backwards compatibility because of existing
    classes with names such as object, string, etc.

    So, what do you guys think about this? I know many of you wanted
    something like this (including types for return values).

    Personally, I like the type hinting part a lot. The strict type checking is
    something that I don't really love as this will produce lots of code for type
    casting before a function call, instead of having it in the function. For
    example:

    PHP Code:
    <?php

    function foo(int $astring $b) {}


    foo((int) '1');

    foo((int) '2');

    foo((int) '3');

    foo((int) '4');
    Whereas the parameter type hinting solves this problem in one place only,
    generating the same error whenever a certain variable cannot be casted to
    the desired type.
    I'm under construction | http://igstan.ro/

  2. #2
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Amenthes View Post
    Personally, I like the type hinting part a lot. The strict type checking is
    something that I don't really love as this will produce lots of code for type
    casting before a function call, instead of having it in the function.
    Yeah. I'm actually surprised they came up with a proper solution this time. The introduced syntax is pleasant and it actually solves two problems: wanting to accept input strictly of specified types and accepting anything but wanting to cast it explicitly before use. I'm really looking forward to this patch.

  3. #3
    SitePoint Guru bronze trophy TomB's Avatar
    Join Date
    Oct 2005
    Location
    Milton Keynes, UK
    Posts
    996
    Mentioned
    9 Post(s)
    Tagged
    2 Thread(s)
    unless you can do something like:

    PHP Code:
    function foo(int $bar) {
        return 
    $bar;
    }


    function 
    foo(string $bar) {
        return 
    strlen($bar);

    (there is a name for this.. method overloading??)

    The usefullness is rather limited.

  4. #4
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,053
    Mentioned
    66 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by TomB View Post
    unless you can do something like:

    PHP Code:
    function foo(int $bar) {
        return 
    $bar;
    }


    function 
    foo(string $bar) {
        return 
    strlen($bar);

    (there is a name for this.. method overloading??)

    The usefullness is rather limited.
    Yes, method overloading. A feature of C and I believe Java. Without the ability to overload functions in this manner setting up functions to take strict arguments quickly becomes a pain.

    I'm against forced data typing in PHP -- While certainly useful for experienced programmers strong data typing presents a learning barrier for new programmers. You really need to get your hands dirty with some code before you start to realize why datatypes are useful.

    What I've mentioned before, and what would be more useful is the addition of tolerant and strict variables in addition to the existing scalar variables.

    The syntax I recommended is borrowed from Actionscript 2 and 3.

    PHP Code:
    /*Create a normal scalar variable */
    var $a '';

    /* And of course $a 's type can change over time. */
    $a true;
    $a 3;

    /* A tolerant var has it's type declared at creation */
    var $t:int 3;

    /* Put a non matching value in and silent conversion occurs */
    $t '04';
    /* here $t remains an integer and holds the int val of the strin
     * '04' which is 4.
     */
    $t false;
    /* $t will remain an int and be returned to 0.
    $t = 3.4;
    /* $t equals 3 here. */

    /* A strict var throws a recoverable error if the wrong data
     * type is assigned to it. It has a new keyword for declaring
     */

    strict $s 'a string';

    /* $s datatype will be locked to the most restrictive datatype
     * that allows the data to be entered unchanged. Normally
     * with strict vars we want to declare datatype on creation
     */

    strict $s:string 'a string';

    /* and now the next line is an error. */
    $s false;

    /* In actionscript function returns can be cast with the :type
     * syntax as follows */
    function foo $arg ):int

    /* If the function must take specific arguments the strict
     * keyword is again used to declare the function.
     */
    strict function foo $arg:string$arg2:int ):array

    /* These functions must have datatypes declared or
     * an error will occur as in the following example 
     */
    strict function foo $a$b // throws error

    /* Strict functions can be overloaded. This should be
     * easier to code the parser for since only the STRICT
     * functions can overload. Scalar functions cannot
     * be overloaded.
     */
    strict function foo ($a:int):boolean
    strict 
    function foo ($a:string):boolean 
    By using this approach this layer of complexity is couched away from beginning programmers until they actually need it. Experienced programmers can decide if the situation calls for soft or hard datatyping and use the approach that suits that situation increasing the flexibility of the language as a whole.

  5. #5
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As I see it, it's a sad day if this ever gets into the language. We'll basically end up with the verbosity and unwieldiness of a statically typed language, but without any of the benefits. It's a lose-lose.

  6. #6
    SitePoint Guru bronze trophy TomB's Avatar
    Join Date
    Oct 2005
    Location
    Milton Keynes, UK
    Posts
    996
    Mentioned
    9 Post(s)
    Tagged
    2 Thread(s)
    I disagree, there are places where type checking is useful.

    However, it really needs to use loose checks and automatically cast wherever possible, e.g. "Can $foo be represented as a string" rather than "is $foo a string"

    PHP Code:
    function foo(string $str) {
        return 
    $str;    
    }

    class 
    MyObj {
        public function 
    __toString() {
            return 
    'bar';
        }
    }

    echo 
    foo(new MyObj);  //Should print 'bar';
    echo foo(100); //should print '100' 
    Of course we'd really then need magic methods for __to* for all the data types


    but then overloading introduces new problems. Consider:

    PHP Code:
    function foo(int $bar) {
        
    }

    function 
    foo(string $bar) {
        
    }

    function 
    foo(MyObj $bar) {
        
    }

    foo(1);
    foo('1');
    foo(new MyObj); 
    The interpreter now needs to do some sort of 'best match' for each case.

  7. #7
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken View Post
    As I see it, it's a sad day if this ever gets into the language. We'll basically end up with the verbosity and unwieldiness of a statically typed language, but without any of the benefits. It's a lose-lose.
    It will be getting into the language judging from all the internals discussion on the subject, and by the looks of things pretty soon (in the grand scheme of things).

    However, it'll be absolutely optional so there's absolutely no need to change the way you work if you don't want to.

    Personally, I like already being able to hint at arrays, classes, interfaces at the moment and this appears a logical extension to that. I'm still on the fence as to whether arguments should be type-casted as part of the process as that goes against what we have already (with function myfunc(array $class), if $class isn't an array then there is no attempt to cast it to one) but I can see the usefulness.
    Salathe
    Software Developer and PHP Manual Author.

  8. #8
    SitePoint Zealot GOPalmer's Avatar
    Join Date
    Jan 2009
    Location
    Wiltshire, UK
    Posts
    125
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm actually really looking forward to seeing this. I do think it needs to be type casted though, I think it will cause no end of issues for those new to php if its not. The loose typing is very forgiving for new programmers and typing is often overlooked by many. With strictly typed parameters they could run into unexpected problems.

  9. #9
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken View Post
    As I see it, it's a sad day if this ever gets into the language. We'll basically end up with the verbosity and unwieldiness of a statically typed language, but without any of the benefits. It's a lose-lose.
    Full ACK. PHP should stick to it's roots.

    The whole problem is that many features are added for these hardcore
    full time php programmers, suffering from ruby/python/java/<any> envy.
    Hoping that php with some of their features will gain some academic
    respect. This is wrong (and polemic ).
    Wrong, because less educated "programmers" will suffer from any feature
    that they have to learn. Wrong, because many features will not be integral
    enough and will cause more confusion and frustration.

    An integral solution is crucial (here MY python envy kicks in). Type hint's
    and type cast's only solve problems to people that already care about this
    problems. They can already solve them. I understand the fact that this
    shortcuts will save some lines of code. But i don't think it's worth to hack
    the core if they're not integral and pure convenience (i.e. benefits of static
    types are really integral and would also boost performance. But who cares ).

    Do you really want to hack the core for a problem that is so simple?
    PHP Code:
    function foo($int$str$arr){
      
    /*
       * typecheck() checks if a variables changes
       * after and roundtrip cast.
       * (an additional arg could control if it's throw an exception or triggers an error)
      */
      
    typecheck_array(func_get_args(), 'int''str''arr');

    (correct me if there are cases that this solution will not cover)

    Note that a really useful feature like traits could add domain specific
    validation functionality easily.

    Conclusion:
    To keep PHP noob programmer friendly and simple, syntactical
    features should be kept down to a minimum. Advanced or academic
    features should go where the caring people hang out, OOP space.
    The latter shouldn't encourage a feature bloat, but sane integral
    and really useful features that can change the whole game.
    PPP, Static, Typehints, Return Typehints, Namespaces are all not that
    useful as you think. How much could do UTF8 and traits support do
    for us? How long we have to wait for that, while some guys cripple PHP?

    Looks like many php core developers just waste their time, like
    i tend to do. humans^^

  10. #10
    SitePoint Wizard Ren's Avatar
    Join Date
    Aug 2003
    Location
    UK
    Posts
    1,060
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Think its a good thing. It'll can actually reduce the amount of code required for communicating to another systems where the typing is a lot more strict. Databases and so on.

    Potentially could make PHP run faster too, as it gains more knowledge about the code it is running.

  11. #11
    SitePoint Wizard Ren's Avatar
    Join Date
    Aug 2003
    Location
    UK
    Posts
    1,060
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by elias View Post
    Do you really want to hack the core for a problem that is so simple?
    PHP Code:
    function foo($int$str$arr){
      
    /*
       * typecheck() checks if a variables changes
       * after and roundtrip cast.
       * (an additional arg could control if it's throw an exception or triggers an error)
      */
      
    typecheck_array(func_get_args(), 'int''str''arr');

    (correct me if there are cases that this solution will not cover)
    References...

  12. #12
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ren View Post
    References...
    Huh? checking for references? that is weird...

  13. #13
    SitePoint Wizard Ren's Avatar
    Join Date
    Aug 2003
    Location
    UK
    Posts
    1,060
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by elias View Post
    Huh? checking for references? that is weird...
    Not at all.

    Just about every database & api, has support for input/output parameters.

    PHP Code:
    function anStoredProcedure(int &$param)
    {
          ...
          
    $statement->bindParam(1$paramPDO::PARAM_INPUT_OUTPUT PDO::PARAM_INT);
          ...


  14. #14
    PHP/Rails Developer Czaries's Avatar
    Join Date
    May 2004
    Location
    Central USA
    Posts
    806
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As far as PHP goes, I think the dynamically type-casted arguments actually make a lot of sense. I could easily see good use for them, especially for cases of preventing SQL injection.

    I really hate the idea of strictness for PHP though, on almost any occasion. PHP isn't really like other languages with variables being a specific type, and it would move PHP in a bad direction. PHP needs to be flexible, not strict. Automatic casting is flexible. Strict type checks are not.

  15. #15
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I agree with the strictness idea - I think that if an variable is able to be typecast to a certain type, it should be converted automatically - though the (int)$var allows for that with the added flexibility of forcing types too.

    I've been waiting for typed parameters for a long time.

    PHP has a big problem looming. Whilst it is a great language for beginners to start on, it also has some downfalls compared to other languages which, if implemented, would make PHP harder to fully learn for the beginners. It's going to go one way or the other, and it seems to be going the right way for me - implementing more useful/advanced features whilst allowing users to write PHP without them.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  16. #16
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ren View Post
    Not at all.

    Just about every database & api, has support for input/output parameters.

    PHP Code:
    function anStoredProcedure(int &$param)
    {
          ...
          
    $statement->bindParam(1$paramPDO::PARAM_INPUT_OUTPUT PDO::PARAM_INT);
          ...

    this is not an reference check, it's an enforcment/declaration/whatever.
    -> different topic

    [edit]
    Quote Originally Posted by Czaries View Post
    As far as PHP goes, I think the dynamically type-casted arguments actually make a lot of sense. I could easily see good use for them, especially for cases of preventing SQL injection.
    because it's optional it will never prevent anything for ppl that don't use it.

  17. #17
    SitePoint Zealot Amenthes's Avatar
    Join Date
    Oct 2006
    Location
    Bucharest, Romania
    Posts
    143
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ren View Post
    Potentially could make PHP run faster too, as it gains more knowledge about the code it is running.
    My C skills are rather limited, but as far as I can see in the patch,
    the only compile-time checking is for assuring that default arguments respect
    the parameter type. Otherwise, the checks are done at runtime, so at least
    for the moment I see no improvement in speed.

    Actually, this runtime checks make me wonder what's so useful about strict
    type checking in PHP. Assuming I have this function:

    PHP Code:
    function foo(int $i) {} 
    and, at some point in the script execution, it somehow receives a numeric
    string argument, like '1':

    PHP Code:
    foo('1'); 
    What does it happen right now? An E_RECOVERABLE_ERROR is issued, where
    such an error is (quote from the manual):

    Catchable fatal error. It indicates that a probably dangerous error
    occured, but did not leave the Engine in an unstable state. If the error is not
    caught by a user defined handle (see also set_error_handler()), the
    application aborts as it was an E_ERROR.
    That does not sound too good for me. I can't prepend every function call in
    my code with the @ operator to suppress errors. That's why I proposed that if
    the features gets in the PHP core at all, it should at least throw exceptions
    whenever an argument's type does not match the type of the parameter.

    It was refused because that this is not the way PHP handles errors, and I
    agree with this reasoning. Then someone proposed a thing that I'd do it
    myself, creating an error handler that throws exceptions for such situations.

    So, what would be so useful about strict type checking if it's not compile-time?
    Runtime means that I have to jump yet another hoop, creating an error handler.

    Oh, and if you say that this whole type checking is optional, then I should
    clarify that I'm thinking more about abuse in third party libraries. I'm pretty
    sure Zend Framework (for example) will be filled with such type checks.
    I'm under construction | http://igstan.ro/

  18. #18
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Amenthes View Post
    My C skills are rather limited, but as far as I can see in the patch,
    the only compile-time checking is for assuring that default arguments respect
    the parameter type. Otherwise, the checks are done at runtime, so at least
    for the moment I see no improvement in speed.
    That is correct. There is no speed improvement to be had when using this, the variables will be just as dynamically typed as always, all this does is check or cast the type at the time it is passed to the function.

    Actually, this runtime checks make me wonder what's so useful about strict type checking in PHP. Assuming I have this function:
    PHP Code:
    function foo(int $i) {} 
    and, at some point in the script execution, it somehow receives a numeric
    string argument, like '1'
    Emphasis mine. If a function has a signature such as above, it's your job as the caller to make sure the parameters are appropriate. This is in no way different to what you should already be doing - it's just another way of enforcing it, and like any other tool in the box it is appropriate in some situations and inappropriate in others. I do agree that the type-casting version is one I'll likely be using more, just to declare that whatever you pass in I'll be handling it as, say, an array anyway.

    Oh, and if you say that this whole type checking is optional, then I should
    clarify that I'm thinking more about abuse in third party libraries. I'm pretty
    sure Zend Framework (for example) will be filled with such type checks.
    If you ask me, ZF seems like a pinnacle of leniency. A lot of the methods accept four or more different kinds of arguments with different handling for each - Zend_Date's constructor, for instance. This is for ease of use, of course, and I don't expect it to change in the near future.

  19. #19
    SitePoint Zealot Amenthes's Avatar
    Join Date
    Oct 2006
    Location
    Bucharest, Romania
    Posts
    143
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ezku View Post
    Emphasis mine. If a function has a signature such as above, it's your job as the caller to make sure the parameters are appropriate. This is in no way different to what you should already be doing - it's just another way of enforcing it, and like any other tool in the box it is appropriate in some situations and inappropriate in others. I do agree that the type-casting version is one I'll likely be using more, just to declare that whatever you pass in I'll be handling it as, say, an array anyway.
    Thanks for emphasis, I should have put it there myself as the wording was well
    thought. My point is this one. The purpose of strict type checking is to help us
    reduce the number of bugs in our application. As the checks aren't done compile
    time, we'll have to wait until the application breaks somehow. Either on production
    server, either in our test cases, or somewhere else. So, if its purpose is to help
    me reduce bugs, how do I catch these errors? Before, these checks were
    done inside the function, as elias showed with his typecheck_array() function.
    With strict type I have to move the error checking inside a callback function and
    register it with set_error_handler. Then there's another problem. Anytime such
    an error happens we usually need to take appropriate measures on the offending
    code, which is rather hard because the error was caught in a callback function.
    The only solution I see is some kind of goto and Exceptions fit this purpose well.
    So, at least for me, I'll be throwing exceptions from an error handler whenever
    some library that I use has these type checks.

    Quote Originally Posted by Ezku View Post
    If you ask me, ZF seems like a pinnacle of leniency. A lot of the methods accept four or more different kinds of arguments with different handling for each - Zend_Date's constructor, for instance. This is for ease of use, of course, and I don't expect it to change in the near future.
    You're actually right about that, except maybe for parameters that should
    receive objects. Those are almost always class hinted.
    I'm under construction | http://igstan.ro/

  20. #20
    SitePoint Wizard Ren's Avatar
    Join Date
    Aug 2003
    Location
    UK
    Posts
    1,060
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Amenthes View Post
    My C skills are rather limited, but as far as I can see in the patch,
    the only compile-time checking is for assuring that default arguments respect
    the parameter type. Otherwise, the checks are done at runtime, so at least
    for the moment I see no improvement in speed.
    I said Potentially.

    At the moment every single variable access causes PHP to look up the type of the variable.
    What could happen in the future, once PHP seen an assertion about the type of variable, it can assume it.

    There have been other talk on internals about various forms of data flow analysis and this type checking would add useful information.

  21. #21
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Amenthes View Post
    With strict type I have to move the error checking inside a callback function and register it with set_error_handler.
    You can register an error handler, which throws an exception. This effectively turns errors into exceptions. I'm using this as part of my default setup already.

  22. #22
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ezku View Post
    Emphasis mine. If a function has a signature such as above, it's your job as the caller to make sure the parameters are appropriate. This is in no way different to what you should already be doing - it's just another way of enforcing it, and like any other tool in the box it is appropriate in some situations and inappropriate in others.
    Why do you want to force the caller to use a particular implementation, when all you need is conformance to an interface? The only thing this accomplishes, is to add a lot of bureaucracy and book-keeping to the language.

  23. #23
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    lol, just read into the internals discussion a little.
    it's a joke! (and ilia in the center of it)

    *plonk*

  24. #24
    SitePoint Zealot
    Join Date
    Sep 2005
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'd welcome this addition if only to see improved refactoring capabilities appear in IDEs.

  25. #25
    SitePoint Addict wibble wobble's Avatar
    Join Date
    Dec 2008
    Posts
    242
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've been hoping for this for a while now. Making this optional is of course critical (nobody is going to go through years of code just to upgrade versions!), so I don't see how it could ever be a bad thing. Beginners don't need to know about it and nobody has to use it if they don't want to.

    This is essential for overloading, and that is a feature I would LOVE to see in PHP.
    Find freelance jobs from all the major sites in one place:
    on twitter / on the web / twitter rss feed


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •