Why no overloading in PHP5?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
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 "overloading"
(http://no.php.net/manual/en/language.oop5.overloading.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 "overloading" 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 "overloading" 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">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)




Re: Why no overloading in PHP5?

["Followup-To:" header set to comp.lang.php.]
Quoted text here. Click to load it

What yo define as "overloading" can be achieved with
(and the fact that php has weak-typing)

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

Re: Why no overloading in PHP5?

Quoted text here. Click to load it

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:

Quoted text here. Click to load it

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.



Re: Why no overloading in PHP5?

Quoted text here. Click to load it

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.

Re: Why no overloading in PHP5?

Quoted text here. Click to load it

That was kind of implied in my question...: "Why no (Java/C++ like)
overloading in PHP5?" I hardly think what PHP describes as "overloading"
(__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").

Quoted text here. Click to load it

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

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,

Quoted text here. Click to load it

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

Quoted text here. Click to load it

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.



Re: Why no overloading in PHP5?

Quoted text here. Click to load it

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.

Quoted text here. Click to load it
Quoted text here. Click to load it

What's wrong with

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

Make it easier to share code behind the different types too.

Quoted text here. Click to load it

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

Re: Why no overloading in PHP5?

Chung Leong wrote:
Quoted text here. Click to load it

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

Quoted text here. Click to load it

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.



Re: Why no overloading in PHP5?

Quoted text here. Click to load it

In the case of printing object, how else could you have implemented it? I
mean if it's a third party class, you have no access to its properties and
no idea how the data should be formatted.

There aren't that many scalar types in PHP. About the only ones where the
default type-conversion might be inadequate are boolean, null, and float. So
six if clauses--hardly something to sweat about.

Re: Why no overloading in PHP5?

Chung Leong wrote:
Quoted text here. Click to load it
it? I
Quoted text here. Click to load it
properties and

With conventional overloading you wouldn't need a "dispatcher" object,
and could simply provide an overloaded function:

function printer(SomeType $value)
  // Print code here

Yes, you still need to know how to print it, to implement that
function, but my point was about the dispatcher being a "dependency
hog", which, unless you use something like the code in my posting, has
to be modified for each new type added. There's no way to include just
one simple function for the type you want to print.

Quoted text here. Click to load it
float. So

Sure, but my main concern was the user-defined types (also, printing is
a bad example, since they have the toString() method, but it was just
an example).



Re: Why no overloading in PHP5?

Quoted text here. Click to load it

....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+$object", 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).



Re: Why no overloading in PHP5?

 .oO(Terje Slettebř)

Quoted text here. Click to load it

I wouldn't call it overloading at all, it's compiler magic (like using
foreach for iteration on objects).

Quoted text here. Click to load it

In some cases you can solve such issues with interfaces.


Re: Why no overloading in PHP5?

Quoted text here. Click to load it

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



Re: Why no overloading in PHP5?

Terje Slettebř scribbled something along the lines of:
Quoted text here. Click to load it

Yes, but PHP has only recently evolved into a (less or more) OOP
language and was never meant to care about types.
The entire problem of user-defined types only exists when you're using
instances of classes (i.e. objects).

Without classes PHP's approach works well. Once you're using classes,
you need to be a bit more careful.

The OCP may be a bit harmed by PHP's approach, but traditional function
overloading would not work in PHP because of the way it treats types.

I think in PHP it's better to think of classes as something different
than types. An object is of type "object", so to say.
It seems awfully wrong from the perspective of a C++ or Java programmer
but we're not talking about C++ or Java anyway.

Arrays are very different from those in C++ too so I don't see what your
problem is.

As for overloading in PHP, I think the name is descriptive and correct,
but I can see why you were confused about its use.


Re: Why no overloading in PHP5?

 .oO(Terje Slettebř)

Quoted text here. Click to load it

How would you implement it without strong typing?

Quoted text here. Click to load it

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.

Quoted text here. Click to load it

You can achieve the same result in PHP. The only difference is the

Quoted text here. Click to load it

print_r() is not about printing arrays.


Re: Why no overloading in PHP5?

Quoted text here. Click to load it
Quoted text here. Click to load it

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

Quoted text here. Click to load it

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.



Re: Why no overloading in PHP5?

On Wed, 26 Jan 2005 00:49:40 +0100, "Terje Slettebř"

Quoted text here. Click to load it

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

function AddWidget1($widget) {
    // Add an object of type Widget1

function AddWidget2($widget) {
    // Add an object of type Widget2

function __Call($methodName, $arguments)
    $className = get_class ($arugments[0]);
    if (method_exists($methodName & $className)) {
        call_user_func_array($methodName & $className,

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

Re: Why no overloading in PHP5?

Terje Slettebř wrote:
Quoted text here. Click to load it

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($var)) {
        // do something...
    else if(is_a('MyObject', $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($var)) {
        printArray($var);    // another function
    else if(is_a('MyObject', $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.


Re: Why no overloading in PHP5?

(Changing thread only to comp.lang.php)

Quoted text here. Click to load it

Function overloading is still one kind of overloading, so your correction is
incorrect. :)

Quoted text here. Click to load it

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.

Quoted text here. Click to load it

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

"Overloading 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;


Quoted text here. Click to load it


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?

Quoted text here. Click to load it

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

Quoted text here. Click to load it

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++).

Quoted text here. Click to load it

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_object($var) ? get_class($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.


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();


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.



Site Timeline