PHP5: type hinting with optional arguments

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rob Long

    PHP5: type hinting with optional arguments

    Hey,

    I've just noticed a somewhat annoying feature with PHP5 type hinting.

    You cannot hint types on optional arguments like this:

    class MyClass
    {
    function someFunc(Type1 $arg1, Type2 $arg2 = new Type2()) { }

    //or
    function someFunc(Type1 $arg1, Type2 $arg2 = null) { }

    //or
    function someFunc(Type1 $arg1, Type2 $arg2 = Type2::getInsta nce()) { }
    }

    In fact, there doesn't seem to be any way to do this. I guess you could do
    something with global variables, but no thanks....

    Any ideas??

    Rob Long.
  • Berislav Lopac

    #2
    Re: type hinting with optional arguments

    Rob Long wrote:[color=blue]
    > Hey,
    >
    > I've just noticed a somewhat annoying feature with PHP5 type hinting.
    >
    > You cannot hint types on optional arguments like this:
    >
    > class MyClass
    > {
    > function someFunc(Type1 $arg1, Type2 $arg2 = new Type2()) { }
    >
    > //or
    > function someFunc(Type1 $arg1, Type2 $arg2 = null) { }
    >
    > //or
    > function someFunc(Type1 $arg1, Type2 $arg2 = Type2::getInsta nce()) { }
    > }
    >
    > In fact, there doesn't seem to be any way to do this. I guess you
    > could do something with global variables, but no thanks....
    >
    > Any ideas??[/color]

    IMO, it's only logical. Optional arguments need to have a literal value as
    the default, and in your examples above only null is a literal value; others
    are expressions, which are not allowed in optional argumetn definitions.

    Remember that PHP is dynamically typed language; there is nothing preventing
    you from:

    function Function($obj = null) {}

    $object = new Class();

    Function($objec t);

    Berislav


    --
    If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
    Groucho, Chico, and Harpo, then Usenet is Zeppo.


    Comment

    • Rob Long

      #3
      Re: type hinting with optional arguments

      "Berislav Lopac" <berislav.lopac @dimedia.hr> wrote in message news:<cajoc5[color=blue]
      > IMO, it's only logical. Optional arguments need to have a literal value as
      > the default, and in your examples above only null is a literal value; others
      > are expressions, which are not allowed in optional argumetn definitions.
      >
      > Remember that PHP is dynamically typed language; there is nothing preventing
      > you from:
      >
      > function Function($obj = null) {}
      >
      > $object = new Class();
      >
      > Function($objec t);
      >
      > Berislav[/color]

      I disagree. The whole point of type hiniting is to provide a runtime
      contract between the calling code and the called function. Why is it
      logical that mandatory arguments should be hinted and optional
      arguments should not? Especially considering the fact that there is no
      function overloading in PHP.

      I realise that PHP is dynamically typed, which is precisely why type
      hinting was implemented - in order to reduce errors. Of course there
      are workarounds, such as:

      Class MyClass
      {
      function someFunc(Type1 $arg1, $arg2 = null)
      {
      if (!is_null($arg2 ) && !($arg2 instanceof Type2))
      {
      throw new IllegalArgument Exception();
      }
      }
      }

      But we may as well do away with type hinting altogther and provide
      runtime type-checking with the is_a() functions.

      Rob Long.

      Comment

      • Phil Roberts

        #4
        Re: type hinting with optional arguments

        bobalong@gmx.ne t (Rob Long) emerged reluctantly from the curtain
        and staggered drunkenly up to the mic. In a cracked and slurred
        voice he muttered:
        [color=blue]
        > I disagree. The whole point of type hiniting is to provide a
        > runtime contract between the calling code and the called
        > function. Why is it logical that mandatory arguments should be
        > hinted and optional arguments should not? Especially considering
        > the fact that there is no function overloading in PHP.[/color]

        Type hinting in PHP5 only applies to objects anyway, and with the new
        object model all objects are passed by reference. Default parameters
        were only ever available to variables passed by value.

        --
        Phil Roberts | Without me its just aweso. | http://www.flatnet.net/

        "I don't hate MurphyInOhio, I pity the fool!"
        - Mr T.

        Comment

        • Rob Long

          #5
          Re: type hinting with optional arguments

          Phil Roberts <philrob@HOLYfl atnetSHIT.net> wrote in message news:<Xns9508C7 9B5C8F5philrobe rts@216.196.97. 132>...[color=blue]
          > Type hinting in PHP5 only applies to objects anyway, and with the new
          > object model all objects are passed by reference. Default parameters
          > were only ever available to variables passed by value.[/color]

          OK, I think I may have to further explain the point of my question.
          Answer these simple questions:

          1. Is there function overloading in PHP?
          2. Why does PHP not need function overloading, like languages such as
          Java do?

          When you've done that you come to the conclusion that the workaround
          for having no function overloading is default arguments. So far so
          good...

          ...Until type hinting comes along, which, IMO, is a partially
          implemented feature if it doesn't allow for hinting on optional
          arguments. I think people are getting bogged down in syntax here...
          saying things like "you can't have expressions in arguemnts
          definitions." I really couldn't care less about having expressions in
          argument defintions...

          function someFunct(Type1 $arg1, Type2 $arg2 = new Type2()) { }

          or

          function someFunct(Type1 $arg1, Type2 $arg2 = Type2::getInsta nce()) {
          }

          ....IS ugly, which is why there should be a new syntax for optional
          (hinted) arguments in PHP5, such as:

          function someFunc(Type1 $arg1, ? Type2 $arg2)

          or

          function someFunc(Type1 $arg1, [Type2 $arg2], [Type3 $arg3]) etc
          etc...

          Just to say "well that's the way it works" isn't very helpful, nor is
          it informative.

          Comment

          • Phil Roberts

            #6
            Re: type hinting with optional arguments

            bobalong@gmx.ne t (Rob Long) emerged reluctantly from the curtain
            and staggered drunkenly up to the mic. In a cracked and slurred
            voice he muttered:
            [color=blue]
            > 1. Is there function overloading in PHP?
            > 2. Why does PHP not need function overloading, like languages
            > such as Java do?
            >[/color]

            1. No
            2. Because there are numerous workarounds. I've never had any need
            for it myself...

            --
            Phil Roberts | Without me its just aweso. | http://www.flatnet.net/

            "I don't hate MurphyInOhio, I pity the fool!"
            - Mr T.

            Comment

            • Xellos[FSO]

              #7
              Re: type hinting with optional arguments

              > 1. No[color=blue]
              > 2. Because there are numerous workarounds. I've never had any need
              > for it myself...[/color]

              To Phil: You are completely missing Rob's point. And those two questions
              were rhetorical. Your teacher - back in HS - must have explained those,
              while you were sleeping...

              To Rob: since type hinting in PHP only applies to objects and default
              values can only be basic data types, so there is no practical use of
              hinting for default values.

              The standard situation:

              function someFunc($objec toOfTypeCoolExp ected = NULL) {}
              or if you wish:
              function someFunc($objec toOfTypeCoolExp ected = 'There was no object
              given') {}

              In both cases you should hint two types: type NULL or string in addition
              to object type 'Cool'. And as we know it - we can't hint basic types...
              (which is bad IMO)

              The other way of doing this would be:

              function someFunc($objec toOfTypeCoolExp ected =
              $GLOBALS['defaultCoolObj ectToUse']) {}

              Now both situations (default value and given parameter) could be of the
              same type and thus be hinted with one object type. The thing is that this
              is a bad coding example, as you shouldn't really expect that there will be
              some variable declared in the global scope, when the function is called. I
              know you can code this like that, but you shouldn't.

              Perfect solution would be:

              function someFunc($objec toOfTypeCoolExp ected = new Cool()) {}

              This way you could hint the type and expect proper results. Too bad
              dynamic default parameters aren't allowed.

              Discuss.

              Kind regards,
              Adam Wróbel
              aka Xellos[FSO]
              --
              Experience is what you get when you don't read directions.

              Mail: xellos@xellos.i nfo
              WWW: http://xellos.info
              GG: 2369996

              Comment

              • Rob Long

                #8
                Re: type hinting with optional arguments

                > To Rob: since type hinting in PHP only applies to objects and default[color=blue]
                > values can only be basic data types, so there is no practical use of
                > hinting for default values.[/color]

                Well, you CAN pass objects as default values, you just can't hint them.
                If you provide explicit checking combined with the excpetion mechanism
                then you can achieve the same effect as hinting, but it's so much more
                hassle and error-prone!
                [color=blue]
                > The standard situation:
                >
                > function someFunc($objec toOfTypeCoolExp ected = NULL) {}
                > or if you wish:
                > function someFunc($objec toOfTypeCoolExp ected = 'There was no object
                > given') {}
                >
                > In both cases you should hint two types: type NULL or string in addition
                > to object type 'Cool'. And as we know it - we can't hint basic types...
                > (which is bad IMO)[/color]

                Yeah. You can use the checking I describe above to provide your own hinting,
                even on basic types, but you've still got to do this and it requires effort
                and discipline on the part of the developer.

                Compare

                function someFunc(int $x, int $y, MyType $mt, Type2 $at = new Type2()) {
                //...
                }

                with

                function someFunc($x, $y, MyType $mt, $at = null) {
                if (!is_integer($x ))
                {
                throw new IllegalArgument Exception("Firs t argument must be of " .
                type: integer");
                }

                if (!is_integer($y ))
                {
                throw new IllegalArgument Exception("Seco nd argument must be of " .
                type: integer");
                }

                if (!is_null($at))
                {
                if (!($at instanceof AnotherType))
                {
                throw new IllegalArgument Exception("[Optional] fourth argument " .
                "must be of type: AnotherType");
                }
                }
                else $at = new AnotherType();

                //...
                }

                Bloody annoying if you ask me!
                [color=blue]
                > The other way of doing this would be:
                >
                > function someFunc($objec toOfTypeCoolExp ected =
                > $GLOBALS['defaultCoolObj ectToUse']) {}[/color]

                Most developers who are THAT concerned about hinting would shy away
                from globals immediately. This isn't even a solution for me...
                [color=blue]
                > Perfect solution would be:
                >
                > function someFunc($objec toOfTypeCoolExp ected = new Cool()) {}[/color]

                Totally.
                [color=blue]
                >
                > This way you could hint the type and expect proper results. Too bad
                > dynamic default parameters aren't allowed.
                >[/color]

                Regards,
                Rob Long.

                Comment

                • Xellos[FSO]

                  #9
                  Re: type hinting with optional arguments

                  So we agree that this thing is kind of incomplete and really only useful
                  to those parameters that are objects AND do not have default value. That's
                  a BIG limitation for me, but I won't say that I can't live with it...

                  Kind regards,
                  Adam Wróbel
                  aka Xellos[FSO]
                  --
                  Experience is what you get when you don't read directions.

                  Mail: xellos@xellos.i nfo
                  WWW: http://xellos.info
                  GG: 2369996

                  Comment

                  • Rob Long

                    #10
                    Re: type hinting with optional arguments

                    "Xellos[FSO]" <xellosfso@go2. pl> wrote in message news:<opr9otmgf ivloyey@devsdes k>...[color=blue]
                    > So we agree that this thing is kind of incomplete and really only useful
                    > to those parameters that are objects AND do not have default value. That's
                    > a BIG limitation for me, but I won't say that I can't live with it...[/color]

                    Me neither; I love PHP! I mean, until now I've been working around
                    member scope, interfaces, static members etc etc, so this one I can
                    definitely live with.... it's just a shame that it's only partially
                    implemented.

                    Comment

                    Working...