Why no overloading in PHP5?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Terje Slettebø

    Why no overloading in PHP5?

    To round off my trilogy of "why"'s about PHP... :) If this subject have been
    discussed before, I'd appreciate a pointer to it. I again haven't found it
    in a search of the PHP groups.

    The PHP manual mentions "overloadin g"
    (http://no.php.net/manual/en/language...erloading.php), but it isn't
    really overloading at all... Not in the sense it's used in other languages
    supporting overloading (such as C++ and Java). As one of the
    user-contributed notes on that page says, it would be more appropriate to
    call it "dynamic methods and properties". What "overloadin g" in PHP is
    about, is to be able to do $object-><name>(...), and it will call the
    built-in function __call() with <name> and an array of the parameters.

    Since "overloadin g" is used in this rather confusing sense (compared to
    other languages) in PHP, it may be useful with a brief recap of how it works
    in C++ and Java. In these languages, overloading means that you may have
    several (member or non-member) functions with the same name, as long as
    their signature is different (number and type of arguments). Translated to
    PHP, this could look like this:

    function f($a) {...} // #1
    function f($a, $b) {...} // #2
    function f($a, b$, $c) {...} // #3
    function f(Person $a) {...} // # 4

    f(1); // Calls #1
    f(1,"test"); // Calls #2
    f(1,2,3); // Calls #3
    $obj=new Person();
    f($obj); // Calls #4

    The last call would technically also match #1, but the one with type hint
    (Person) might be considered "more specialised".

    This issue has, like type hints for built-in types, been asked in a Zend Q &
    A, such as this one: http://www.zend.com/expert_qa/qas.php?id=10&single=1

    --- Start quote ---

    public Object child() {
    return this.child;
    }
    public Object child(Object p_child) {
    this.child = p_child;
    return this.child();
    }

    So this is what you call function overloading? Questions: - Why is it called
    function overloading? - Why won't it be supported in PHP? (important)

    It is called function overloading because you have two instances of the
    same function name but they differ only by the function arguments. You
    expect the right one to be called according to the arguments. It won't be
    supported by PHP because it doesn't fit in with its dynamically typed value
    paradigm and execution methodology. However, you may reach similar affects
    by using optional function arguments for example:

    public Object child(Object p_child=NULL) {
    if (p_child != NULL) {
    this.child = p_child;
    }
    return this.child;
    }

    --- End quote ---

    Again, I don't find the answer satisfactory, but perhaps someone here can
    convince me?

    Even if PHP has loose/weak typing, then as for type hints for built-in
    types, a value or variable has a specific type at any one time. At the very
    least, one might provide overloading for functions taking arguments of
    user-defined types (objects), in the same way as one provide optional static
    typing in the form of type hints. I.e.:

    function print(Person $p) {...}
    function print(Something $s) {...}

    Comments?

    Regards,

    Terje


  • Tim Van Wassenhove

    #2
    Re: Why no overloading in PHP5?

    ["Followup-To:" header set to comp.lang.php.]
    On 2005-01-22, Terje Slettebø <tslettebo@hotm ail.com> wrote:[color=blue]
    > To round off my trilogy of "why"'s about PHP... :) If this subject have been
    > discussed before, I'd appreciate a pointer to it. I again haven't found it
    > in a search of the PHP groups.[/color]

    What yo define as "overloadin g" can be achieved with

    (and the fact that php has weak-typing)


    --
    Met vriendelijke groeten,
    Tim Van Wassenhove <http://www.timvw.info>

    Comment

    • Terje Slettebø

      #3
      Re: Why no overloading in PHP5?

      "Tim Van Wassenhove" <timvw@users.so urceforge.net> wrote in message
      news:35g9fqF4kf a5kU2@individua l.net...[color=blue]
      > ["Followup-To:" header set to comp.lang.php.]
      > On 2005-01-22, Terje Slettebø <tslettebo@hotm ail.com> wrote:[color=green]
      > > To round off my trilogy of "why"'s about PHP... :) If this subject have[/color][/color]
      been[color=blue][color=green]
      > > discussed before, I'd appreciate a pointer to it. I again haven't found[/color][/color]
      it[color=blue][color=green]
      > > in a search of the PHP groups.[/color]
      >
      > What yo define as "overloadin g" can be achieved with
      > http://docs.php.net/en/language.func...iable-arg-list
      > (and the fact that php has weak-typing)[/color]

      Someone else also mentioned this at the php-general list (I've heard that
      the list and the newsgroup mirror each other, but it seems that whichever
      newsgroup that list is reflected to, it's not this one), and I quote my
      reply here:
      [color=blue]
      >From: "Matthew Weier O'Phinney" <matthew@garden .org>[/color]
      [color=blue]
      > PHP already supports overloading as you're accustomed to it -- the
      > syntax is different, and PHP refers to the practice as "variable-lentgh
      > argument lists". You use func_num_args() , func_get_args() , and
      > func_get_arg() to accomplish it:
      >
      > function someOverloadedF un()
      > {
      > $numargs = func_num_args() ;
      > $args = func_get_args() ;
      > if (0 == $numargs) {
      > return "ERROR!";
      > }
      > if (1 == $numargs) {
      > if (is_string($arg s[0])) {
      > return "Received string: $args[0]";
      > } elseif (is_object($arg s[0])) {
      > return "Received object!";
      > }
      > } elseif ((2 == $numargs)) {
      > return "Received arg0 == $args[0] and arg1 == $args[1]";
      > }
      > // etc.
      > }
      >
      > Yes, this is more cumbersome than providing hints[/color]

      Indeed, and it means all the selection have to be done in _one_ function.
      Sure, varargs can give you some kind of overloading, but as with using
      assert and is_* above, to check for incoming types, you essentially have to
      "manually" provide the overloading (by checking argument number and types,
      and dispatching appropriately), and then the alternative of using
      differently named functions really look more appealing...

      Besides, this makes the "switch function" a dependency hog: Every
      "overloaded " function you add means you have to change it. If it's in a
      third-party library, this may not be useful option.

      Regards,

      Terje


      Comment

      • Chung Leong

        #4
        Re: Why no overloading in PHP5?

        "Terje Slettebø" <tslettebo@hotm ail.com> wrote in message
        news:41f2e340$1 @news.broadpark .no...[color=blue]
        > To round off my trilogy of "why"'s about PHP... :) If this subject have[/color]
        been[color=blue]
        > discussed before, I'd appreciate a pointer to it. I again haven't found it
        > in a search of the PHP groups.[/color]

        Why? Because it wasn't implemented. Just because some languages has a
        feature doesn't mean others should. A better question is why should C++
        style overloading should exist in PHP. Given that PHP isn't strongly type, I
        don't really see the need.

        Default parameter in PHP is far more useful in my opinion. And I don't see a
        good way you can keep that and C++ style overloading.



        Comment

        • Terje Slettebø

          #5
          Re: Why no overloading in PHP5?

          "Chung Leong" <chernyshevsky@ hotmail.com> wrote in message
          news:LK6dnSGtbI GYFmncRVn-tw@comcast.com. ..[color=blue]
          > "Terje Slettebø" <tslettebo@hotm ail.com> wrote in message
          > news:41f2e340$1 @news.broadpark .no...[color=green]
          > > To round off my trilogy of "why"'s about PHP... :) If this subject have[/color]
          > been[color=green]
          > > discussed before, I'd appreciate a pointer to it. I again haven't found[/color][/color]
          it[color=blue][color=green]
          > > in a search of the PHP groups.[/color]
          >
          > Why? Because it wasn't implemented. Just because some languages has a
          > feature doesn't mean others should. A better question is why should C++
          > style overloading should exist in PHP.[/color]

          That was kind of implied in my question...: "Why no (Java/C++ like)
          overloading in PHP5?" I hardly think what PHP describes as "overloadin g"
          (__call(), etc.) can be called overloading - not in the usual meaning of the
          word (although you may implement overloading "manually" that way, as you may
          do OO in C, "manually") .
          [color=blue]
          > Given that PHP isn't strongly type, I don't really see the need.[/color]

          What does that got to do with it? Overloading allows you to do things like:

          function print(array a) { ... }
          function print(MyObject o) { ... }
          function print(int i) { ... }
          ....

          Then you may call "print()" with any kind of variable, and it will print it
          correctly.

          Instead of this general-purpose solution, we have special-purpose functions
          and kludges like in Java, such as print_r(), to print an array (but not a
          non-array, then you need to use print()), toString() functions for objects,
          etc.
          [color=blue]
          > Default parameter in PHP is far more useful in my opinion.[/color]

          Default parameters typically get less useful when you get overloading, but,
          yes, you may get a rather limited something similar with it (however, it
          will only allow you to have optional parameters in the same function, not
          have different functions with the same name, or different kind of arguments
          being dispatched to different functions).
          [color=blue]
          > And I don't see a good way you can keep that and C++ style overloading.[/color]

          C++ has default arguments as well, and there's no problem with that:

          void f(int i) { ... }
          void f(int i = 1) { ... } // Error, redefinition

          In C++, default arguments are not part of the function signature, and
          therefore don't participate in the overload resolution. Therefore, with or
          without default arguments don't change which function is called.

          Regards,

          Terje


          Comment

          • Terje Slettebø

            #6
            Re: Why no overloading in PHP5?

            "Terje Slettebø" <tslettebo@hotm ail.com> wrote in message
            news:41f6a037@n ews.broadpark.n o...[color=blue]
            >
            > I hardly think what PHP describes as "overloadin g"
            > (__call(), etc.) can be called overloading - not in the usual meaning of[/color]
            the[color=blue]
            > word[/color]

            ....Although you can actually overload the subscript operator in PHP5
            ($object[...]), which is a case of operator overloading (as in C++), but
            again, it's a special case: only that operator can be overloaded, and
            there's no function overloading. No way to implement "$object+$objec t", for
            example (which could be useful for things like currency, time, etc.). This
            could also enable generic programming in PHP (being able to implement
            functions that work regardless of the type passed to them).

            Regards,

            Terje


            Comment

            • Michael Fesser

              #7
              Re: Why no overloading in PHP5?

              .oO(Terje Slettebø)
              [color=blue]
              >That was kind of implied in my question...: "Why no (Java/C++ like)
              >overloading in PHP5?"[/color]

              How would you implement it without strong typing?
              [color=blue][color=green]
              >> Given that PHP isn't strongly type, I don't really see the need.[/color]
              >
              >What does that got to do with it? Overloading allows you to do things like:
              >
              >function print(array a) { ... }
              >function print(MyObject o) { ... }
              >function print(int i) { ... }
              >...[/color]

              And in PHP you write one function which accepts them all:

              function print($foo) {...}

              If necessary you can check the current type of $foo inside the function.
              [color=blue]
              >Then you may call "print()" with any kind of variable, and it will print it
              >correctly.[/color]

              You can achieve the same result in PHP. The only difference is the
              implementation.
              [color=blue]
              >Instead of this general-purpose solution, we have special-purpose functions
              >and kludges like in Java, such as print_r(), to print an array (but not a
              >non-array, then you need to use print()), toString() functions for objects,
              >etc.[/color]

              print_r() is not about printing arrays.

              Micha

              Comment

              • Michael Fesser

                #8
                Re: Why no overloading in PHP5?

                .oO(Terje Slettebø)
                [color=blue]
                >...Although you can actually overload the subscript operator in PHP5
                >($object[...]), which is a case of operator overloading (as in C++), but
                >again, it's a special case: only that operator can be overloaded, and
                >there's no function overloading.[/color]

                I wouldn't call it overloading at all, it's compiler magic (like using
                foreach for iteration on objects).
                [color=blue]
                >No way to implement "$object+$objec t", for
                >example (which could be useful for things like currency, time, etc.). This
                >could also enable generic programming in PHP (being able to implement
                >functions that work regardless of the type passed to them).[/color]

                In some cases you can solve such issues with interfaces.

                Micha

                Comment

                • Terje Slettebø

                  #9
                  Re: Why no overloading in PHP5?

                  "Michael Fesser" <netizen@gmx.ne t> wrote in message
                  news:e6edv0dfab i0db38u0qqm0d4k uq3kb2tbm@4ax.c om...[color=blue]
                  > .oO(Terje Slettebø)
                  >[color=green]
                  > >No way to implement "$object+$objec t", for
                  > >example (which could be useful for things like currency, time, etc.).[/color][/color]
                  This[color=blue][color=green]
                  > >could also enable generic programming in PHP (being able to implement
                  > >functions that work regardless of the type passed to them).[/color]
                  >
                  > In some cases you can solve such issues with interfaces.[/color]

                  Yes, for regular function calls. However, if you have a function like:

                  function add($a, $b)
                  {
                  return $a + $b;
                  }

                  then without operator overloading, this function simply can't work for
                  objects of user-defined types (classes).

                  Regards,

                  Terje


                  Comment

                  • Terje Slettebø

                    #10
                    Re: Why no overloading in PHP5?

                    "Michael Fesser" <netizen@gmx.ne t> wrote in message
                    news:9mddv0la2m 6tuel5spgms3d9q mihq410ph@4ax.c om...[color=blue]
                    > .oO(Terje Slettebø)
                    >[color=green]
                    > >That was kind of implied in my question...: "Why no (Java/C++ like)
                    > >overloading in PHP5?"[/color]
                    >
                    > How would you implement it without strong typing?
                    >[color=green][color=darkred]
                    > >> Given that PHP isn't strongly type, I don't really see the need.[/color]
                    > >
                    > >What does that got to do with it? Overloading allows you to do things[/color][/color]
                    like:[color=blue][color=green]
                    > >
                    > >function print(array a) { ... }
                    > >function print(MyObject o) { ... }
                    > >function print(int i) { ... }
                    > >...[/color]
                    >
                    > And in PHP you write one function which accepts them all:
                    >
                    > function print($foo) {...}
                    >
                    > If necessary you can check the current type of $foo inside the function.[/color]

                    *wince* Yes, you can do that. But then you need to modify that function for
                    each type you want to add: it becomes a "blob", a dependency hog, typically
                    a function with a large switch-case (or perhaps implemented a little
                    prettier, but it's still all in one place). This violates the Open-Closed
                    Principle (http://c2.com/cgi/wiki?OpenClosedPrinciple). Unlike real
                    overloading, or inheritance-based polymorphism, you can't just _add_ code,
                    to add or change behaviour.

                    However, come to think of it, you might be able to create a
                    "framework"/function, so that you can call one function, yet it dispatches
                    to other functions, and you won't have to modify that function to add new
                    types, due to being able to call variable functions. That would bring it
                    quite a bit closer to conventional overloading.
                    [color=blue][color=green]
                    > >Instead of this general-purpose solution, we have special-purpose[/color][/color]
                    functions[color=blue][color=green]
                    > >and kludges like in Java, such as print_r(), to print an array (but not a
                    > >non-array, then you need to use print()), toString() functions for[/color][/color]
                    objects,[color=blue][color=green]
                    > >etc.[/color]
                    >
                    > print_r() is not about printing arrays.[/color]

                    It's darn useful for that, anyway. :) However, I realise now that print_r()
                    actually outputs the same as print() for non-arrays, so may be used for any
                    type. However, "print()"/"print_r()" was only an example of a polymorphic
                    function, and the usefulness of being able to add overloads to handle
                    different types.

                    Regards,

                    Terje


                    Comment

                    • Chung Leong

                      #11
                      Re: Why no overloading in PHP5?

                      "Terje Slettebø" <tslettebo@hotm ail.com> wrote in message
                      news:41f6a037@n ews.broadpark.n o...[color=blue]
                      > That was kind of implied in my question...: "Why no (Java/C++ like)
                      > overloading in PHP5?" I hardly think what PHP describes as "overloadin g"
                      > (__call(), etc.) can be called overloading - not in the usual meaning of[/color]
                      the[color=blue]
                      > word (although you may implement overloading "manually" that way, as you[/color]
                      may[color=blue]
                      > do OO in C, "manually") .[/color]

                      I agree that the name is confusing. It really is a kind of dispatch
                      interface. Like most PHP features, it's there for a concrete, practical
                      reason. What the PHP team had in mind was probably SOAP.
                      [color=blue][color=green]
                      > > Given that PHP isn't strongly type, I don't really see the need.[/color]
                      >
                      > What does that got to do with it? Overloading allows you to do things[/color]
                      like:[color=blue]
                      >
                      > function print(array a) { ... }
                      > function print(MyObject o) { ... }
                      > function print(int i) { ... }
                      > ...
                      >
                      > Then you may call "print()" with any kind of variable, and it will print[/color]
                      it[color=blue]
                      > correctly.[/color]

                      What's wrong with

                      function print($a) {
                      if(is_array($a) ) {
                      echo implode(', ', $a);
                      }
                      else if($a instance of PrintInterface) {
                      $a->Print();
                      }
                      else {
                      echo $a;
                      }
                      }

                      Make it easier to share code behind the different types too.
                      [color=blue][color=green]
                      > > Default parameter in PHP is far more useful in my opinion.[/color]
                      >
                      > Default parameters typically get less useful when you get overloading,[/color]
                      but,[color=blue]
                      > yes, you may get a rather limited something similar with it (however, it
                      > will only allow you to have optional parameters in the same function, not
                      > have different functions with the same name, or different kind of[/color]
                      arguments[color=blue]
                      > being dispatched to different functions).
                      >[color=green]
                      > > And I don't see a good way you can keep that and C++ style overloading.[/color]
                      >
                      > C++ has default arguments as well, and there's no problem with that:
                      >
                      > void f(int i) { ... }
                      > void f(int i = 1) { ... } // Error, redefinition
                      >
                      > In C++, default arguments are not part of the function signature, and
                      > therefore don't participate in the overload resolution. Therefore, with or
                      > without default arguments don't change which function is called.[/color]

                      By golly I could be done in C++. I would have sworn that it can't be. Must
                      have gotten it confused with Javascript.


                      Comment

                      • Terje Slettebø

                        #12
                        Re: Why no overloading in PHP5?

                        Chung Leong wrote:[color=blue]
                        > "Terje Slettebø" <tslettebo@hotm ail.com> wrote in message
                        > news:41f6a037@n ews.broadpark.n o...
                        >[color=green]
                        > > Overloading allows you to do things like:
                        > >
                        > > function print(array a) { ... }
                        > > function print(MyObject o) { ... }
                        > > function print(int i) { ... }
                        > > ...
                        > >
                        > > Then you may call "print()" with any kind of variable, and it will[/color][/color]
                        print[color=blue]
                        > it[color=green]
                        > > correctly.[/color]
                        >
                        > What's wrong with
                        >
                        > function print($a) {
                        > if(is_array($a) ) {
                        > echo implode(', ', $a);
                        > }
                        > else if($a instance of PrintInterface) {
                        > $a->Print();
                        > }
                        > else {
                        > echo $a;
                        > }
                        > }[/color]

                        Yes, that's one way, but then the class has to implement the
                        PrintInterface. If it doesn't, e.g. a third party class not
                        implementing that interface, then you can't use the above function.
                        Then you would need to modify it for each type. With only three cases,
                        as above, the code is reasonably clear. However, with many types,
                        unless you make some kind of uniform dispatch mechanism to other
                        functions, it can quickly grow into a rather large and messy
                        switch-case or if-else ladder.

                        (Yes, I know that in PHP there's a special-purpose solution to output
                        in the form of the toString() method, but printing was just an example
                        of overloading, which is a general-purpose solution.)
                        [color=blue]
                        > Make it easier to share code behind the different types too.[/color]

                        That can be done easily by factoring common code out into functions, as
                        well, and delegating to them, as appropriately. Or use interfaces, as
                        in your example, and overload on the interfaces.

                        Regards,

                        Terje

                        Comment

                        • Berislav Lopac

                          #13
                          Re: Why no overloading in PHP5?

                          Terje Slettebø wrote:[color=blue]
                          > "Chung Leong" <chernyshevsky@ hotmail.com> wrote in message
                          > news:LK6dnSGtbI GYFmncRVn-tw@comcast.com. ..[color=green]
                          >> Given that PHP isn't strongly type, I don't really see the need.[/color]
                          >
                          > What does that got to do with it? Overloading allows you to do things
                          > like:
                          >
                          > function print(array a) { ... }
                          > function print(MyObject o) { ... }
                          > function print(int i) { ... }[/color]

                          This is not overloading -- this is *function* overloading.

                          Overload, in its most general sense, is when a unit, depending on the
                          circumstances, does different things. Therefore, the use of the word
                          overloading for the feature that enables various things to be performed when
                          a value is accessed is perfectly valid.

                          As for your original question, i.e. why is there no "classic" overloading in
                          PHP, the answer is at least twofold.

                          For one, it might break backward compatibility, which is very important
                          considering the installed base of PHP4 applications. Since in PHP4 you can't
                          have two functions with same name in the same scope (e.g. a class, or
                          globally), the overloading approach you suggest would break this.

                          For two, as Chung pointed out above, there is no need. In strongly-typed
                          languages, such as Java and C++, the types of method parameters are very
                          important, and you have to set them at compile time; in PHP the type is not
                          important, and it is resolved at runtime.

                          I conclude from your other posts (about visibility) that you think too
                          closely within the constraints you are familiar with. Instead, you should
                          get familiar with the feature of the other language and use them properly.

                          Think about this: even if "classic" overloading would be possible in PHP, is
                          it inherently better than other options? In PHP, the example in your post
                          above would look like this:

                          function print($var) {
                          if(is_array($va r)) {
                          // do something...
                          }
                          else if(is_a('MyObje ct', $var)) {
                          // do something else...
                          }
                          else {
                          // do something completely different...
                          }
                          }

                          I can understand that it's cleaner if you do all this things in different
                          functions, but this is easily remedied like this:

                          function print($var) {
                          if(is_array($va r)) {
                          printArray($var ); // another function
                          }
                          else if(is_a('MyObje ct', $var)) {
                          $var->print() // this is proper OO :)
                          }
                          else {
                          // printing code for everything else
                          }
                          }

                          As Chung pointed, typing strength of a language is extremely important here.

                          Berislav


                          Comment

                          • Terje Slettebø

                            #14
                            Re: Why no overloading in PHP5?

                            (Changing thread only to comp.lang.php)

                            "Berislav Lopac" <berislav.lopac @lopsica.com> wrote in message
                            news:ct822n$trf $1@garrison.glo balnet.hr...[color=blue]
                            > Terje Slettebø wrote:[color=green]
                            > > "Chung Leong" <chernyshevsky@ hotmail.com> wrote in message
                            > > news:LK6dnSGtbI GYFmncRVn-tw@comcast.com. ..[color=darkred]
                            > >> Given that PHP isn't strongly type, I don't really see the need.[/color]
                            > >
                            > > What does that got to do with it? Overloading allows you to do things
                            > > like:
                            > >
                            > > function print(array a) { ... }
                            > > function print(MyObject o) { ... }
                            > > function print(int i) { ... }[/color]
                            >
                            > This is not overloading -- this is *function* overloading.[/color]

                            Function overloading is still one kind of overloading, so your correction is
                            incorrect. :)
                            [color=blue]
                            > Overload, in its most general sense, is when a unit, depending on the
                            > circumstances, does different things.[/color]

                            That's a very broad interpretation, which I haven't heard anywhere else.
                            What you describe is usually called polymorphism (and overloading enables
                            one kind of polymorphisms). In general, the way I have understood
                            overloading, is when you may have several names in the same scope (typically
                            functions) - the names "overload" or coexist with each other.
                            [color=blue]
                            > Therefore, the use of the word
                            > overloading for the feature that enables various things to be performed[/color]
                            when[color=blue]
                            > a value is accessed is perfectly valid.[/color]

                            Do you have a link to something supporting that definition of overloading
                            (outside the PHP community)? Wikipedia defines "overloadin g" as
                            (http://en.wikipedia.org/wiki/Overloading#Overloading):

                            "Overloadin g allows multiple *functions* taking different types to be
                            defined with the same name; the compiler or interpreter automatically calls
                            the right one." (my emphasis)

                            There has also been a suggestion for "class template overloading" in C++,
                            which would mean being able to overload templates (since the parameter lists
                            may distinguish them from each other, as with functions). For those familiar
                            with the syntax, this could look like this:

                            template<class T>
                            class some_template;

                            template<int i> // Different parameter kind
                            class some_template;

                            template<class T1, class T2> // Different number of parameters
                            class some_template;

                            etc.
                            [color=blue]
                            > As for your original question, i.e. why is there no "classic" overloading[/color]
                            in[color=blue]
                            > PHP, the answer is at least twofold.
                            >
                            > For one, it might break backward compatibility, which is very important
                            > considering the installed base of PHP4 applications.[/color]

                            Indeed.
                            [color=blue]
                            > Since in PHP4 you can't
                            > have two functions with same name in the same scope (e.g. a class, or
                            > globally), the overloading approach you suggest would break this.[/color]

                            How can that be? As you say yourself, this is currently illegal, so no valid
                            program may have it today. How can making something previously illegal,
                            legal, break existing programs? This is a classic case of "pure extension"
                            (not breaking backwards compatibility). The same goes for type-hints. Am I
                            missing something?
                            [color=blue]
                            > For two, as Chung pointed out above, there is no need. In strongly-typed
                            > languages, such as Java and C++, the types of method parameters are very
                            > important, and you have to set them at compile time; in PHP the type is[/color]
                            not[color=blue]
                            > important, and it is resolved at runtime.[/color]

                            And this changes what? As I've said before, at any one time, a variable has
                            a well-defined type. Thus, it may be used in overload resolution in a
                            function call. Yes, there may be conversions (like in C++ and Java), so one
                            may need to implement a ranking of the functions to determine "best match".
                            [color=blue]
                            > I conclude from your other posts (about visibility) that you think too
                            > closely within the constraints you are familiar with. Instead, you should
                            > get familiar with the feature of the other language and use them properly.[/color]

                            That about visibility and access was a minor thing. As I said in another
                            post, there may be good reasons for either way (and indeed, both ways were
                            considered during the development of C++).
                            [color=blue]
                            > Think about this: even if "classic" overloading would be possible in PHP,[/color]
                            is[color=blue]
                            > it inherently better than other options? In PHP, the example in your post
                            > above would look like this:
                            >
                            > function print($var) {
                            > if(is_array($va r)) {
                            > // do something...
                            > }
                            > else if(is_a('MyObje ct', $var)) {
                            > // do something else...
                            > }
                            > else {
                            > // do something completely different...
                            > }
                            > }
                            >
                            > I can understand that it's cleaner if you do all this things in different
                            > functions, but this is easily remedied like this:
                            >
                            > function print($var) {
                            > if(is_array($va r)) {
                            > printArray($var ); // another function
                            > }
                            > else if(is_a('MyObje ct', $var)) {
                            > $var->print() // this is proper OO :)
                            > }
                            > else {
                            > // printing code for everything else
                            > }
                            > }[/color]

                            If "MyObject" is an interface (rather unlikely, given the name), then this
                            is the same example as the one to Chung, and, yes, it's a reasonable design.
                            However, it requires that each class you want to print implements that
                            interface (in PHP5 we have a standard interface for this, though,
                            toString(), which is used automatically in certain places (such as "echo
                            $object")). If you want to print a class that is in a third-party library
                            not implementing that interface, and where you can't (or shouldn't) change
                            it, you can't use this approach. However, from this discussion, and from
                            these examples, I've come to think of the following slightly esoteric way
                            that may be used for any type:

                            function printer($var) // Generic version/dispatcher
                            {
                            $function_name= "print_".(is_ob ject($var) ? get_class($var) :
                            gettype($var));

                            call_user_func( $function_name, $var);
                            }

                            "printer", rather than "print" is used, as the latter is taken. A more
                            robust version would enable any number of parameters, but that should be
                            relatively easy.

                            Use:

                            class SomeClass // Some class we can't change
                            {
                            public function get_state()
                            {
                            return "1234";
                            }
                            }

                            // "Overloads" for printer()

                            function print_integer($ var)
                            {
                            echo $var;
                            }

                            function print_SomeClass ($var)
                            {
                            echo $var->get_state();
                            }

                            $a=1;

                            printer($a); // Prints "1"

                            $a=new SomeClass();

                            printer($a); // Prints "1234"

                            This is the closest I've found to function overloading in PHP, and I think
                            it's quite reasonable, given that the dispatcher class printer() never have
                            to be changed, and you classes don't need to implement a particular
                            interface. We can just add a new function, and it will work like with the
                            rest of the types.

                            If, in your example, "MyObject" is an object, rather than an interface,
                            then, no, then it's not "proper OO". Then it's switch-on-type, which kind of
                            simulates how OO works, rather than actually using inheritance-based
                            polymorphism (also known as OO), such as using an interface.

                            Regards,

                            Terje


                            Comment

                            • Wayne

                              #15
                              Re: Why no overloading in PHP5?

                              On Wed, 26 Jan 2005 00:49:40 +0100, "Terje Slettebø"
                              <tslettebo@hotm ail.com> wrote:
                              [color=blue]
                              >However, come to think of it, you might be able to create a
                              >"framework"/function, so that you can call one function, yet it dispatches
                              >to other functions, and you won't have to modify that function to add new
                              >types, due to being able to call variable functions. That would bring it
                              >quite a bit closer to conventional overloading.[/color]

                              Something like PHP5's __Call() method would be useful for this sort of
                              thing. Some rough pseudocode:

                              function AddWidget1($wid get) {
                              // Add an object of type Widget1
                              }

                              function AddWidget2($wid get) {
                              // Add an object of type Widget2
                              }

                              function __Call($methodN ame, $arguments)
                              {
                              $className = get_class ($arugments[0]);
                              if (method_exists( $methodName & $className)) {
                              call_user_func_ array($methodNa me & $className,
                              $arugments)
                              }
                              }

                              Obviously __Call would have to be more complicated than this simple
                              example but it does give you overloading.

                              Comment

                              Working...