473,704 Members | 2,293 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
Jul 17 '05 #1
17 4717
["Followup-To:" header set to comp.lang.php.]
On 2005-01-22, Terje Slettebø <ts*******@hotm ail.com> wrote:
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.


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)
--
Met vriendelijke groeten,
Tim Van Wassenhove <http://www.timvw.info>
Jul 17 '05 #2
"Tim Van Wassenhove" <ti***@users.so urceforge.net> wrote in message
news:35******** *****@individua l.net...
["Followup-To:" header set to comp.lang.php.]
On 2005-01-22, Terje Slettebø <ts*******@hotm ail.com> wrote:
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.
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)


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:
From: "Matthew Weier O'Phinney" <ma*****@garden .org> 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


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
Jul 17 '05 #3
"Terje Slettebø" <ts*******@hotm ail.com> wrote in message
news:41******** @news.broadpark .no...
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.


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.

Jul 17 '05 #4
"Chung Leong" <ch***********@ hotmail.com> wrote in message
news:LK******** ************@co mcast.com...
"Terje Slettebø" <ts*******@hotm ail.com> wrote in message
news:41******** @news.broadpark .no...
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.


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.


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") .
Given that PHP isn't strongly type, I don't really see the need.
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.
Default parameter in PHP is far more useful in my opinion.
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).
And I don't see a good way you can keep that and C++ style overloading.


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
Jul 17 '05 #5
"Terje Slettebø" <ts*******@hotm ail.com> wrote in message
news:41******@n ews.broadpark.n o...

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 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
Jul 17 '05 #6
.oO(Terje Slettebø)
That was kind of implied in my question...: "Why no (Java/C++ like)
overloading in PHP5?"
How would you implement it without strong typing?
Given that PHP isn't strongly type, I don't really see the need.


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


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.
Then you may call "print()" with any kind of variable, and it will print it
correctly.
You can achieve the same result in PHP. The only difference is the
implementation.
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.


print_r() is not about printing arrays.

Micha
Jul 17 '05 #7
.oO(Terje Slettebø)
...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.
I wouldn't call it overloading at all, it's compiler magic (like using
foreach for iteration on objects).
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).


In some cases you can solve such issues with interfaces.

Micha
Jul 17 '05 #8
"Michael Fesser" <ne*****@gmx.ne t> wrote in message
news:e6******** *************** *********@4ax.c om...
.oO(Terje Slettebø)
No way to implement "$object+$objec t", for
example (which could be useful for things like currency, time, etc.). Thiscould also enable generic programming in PHP (being able to implement
functions that work regardless of the type passed to them).


In some cases you can solve such issues with interfaces.


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
Jul 17 '05 #9
"Michael Fesser" <ne*****@gmx.ne t> wrote in message
news:9m******** *************** *********@4ax.c om...
.oO(Terje Slettebø)
That was kind of implied in my question...: "Why no (Java/C++ like)
overloading in PHP5?"


How would you implement it without strong typing?
Given that PHP isn't strongly type, I don't really see the need.


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


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.


*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.
Instead of this general-purpose solution, we have special-purpose functionsand 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.


print_r() is not about printing arrays.


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
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2984
by: Rob Ristroph | last post by:
I have tried out PHP 5 for the first time (with assistance from this group -- thanks!). The people I was working with have a site that uses lots of php objects. They are having problems with speed. They had a vague idea that PHP5 has improved handling of objects over PHP4, so it would probably be faster also. In fact it seems slower. We did a few timing loops, in which a a number of objects were created and and members were...
0
1359
by: Zurab Davitiani | last post by:
Just want to note few improvements I saw, beyond obvious, while porting my packages to PHP5 (in case anyone is interested): - garbage collection seems to have much improved compared to PHP4; and I don't mean for the session files and data, but for objects and variables while the script is running; - the undocumented clone() function to create copies of objects; - much better implementation of overloading;
11
10583
by: neur0maniak | last post by:
Hi, I've been eager to try out PHP5, so I've dumped it on my little dev machine. It's running WinXP with IIS5. I've put the php-cgi.exe in the "mappings" page as I'm used to doing with PHP4. I've got my php.ini all set in C:\Windows. I created an index.php containing: <?php phpinfo(); ?> When I try to view the page, I get "HTTP 400 - Bad Request".
4
5837
by: badbetty | last post by:
Dear Googlers I have installed PHP5 to run on WinXP against Apache 2. It works! ie. I have tested a few simple scripts and a basic xml document parse. I now want to try the XSL extension so I can transform xml docs. Having copied the php_xsl.dll to a directory where it can be found and done the uncommenting in php.ini, it still will not work. The script I
0
1622
by: zimba | last post by:
Hello ! If somebody is interested, here is a small hack I've done today. There are still some curious effects, but I'm pretty satisfied by the results, since PHP is not very flexible. Let me know what you think, I'm looking into talking about somethin ;)
5
2158
by: Aziz | last post by:
Hi, I've recently contacted technical service of a web hosting company and asked them wheter or not they're gonna upgrade to PHP5 and MySQL5. Here's a quote from their response which confused me a little: "As php5 and mysql5 are still beta versions we don't install beta versions on production servers due to secure reasons, we install only current working versions on production servers"
4
32216
by: emrahayanoglu | last post by:
Hello Everyone, I looked everywhere for that problem. Does anyone know that how can i overload constructor function in php 5? Best Regards, Emrah Ayanoglu
3
5779
by: deciacco | last post by:
I was wondering if there was a way to do operator overlaoding in php like you can in c++. In c++ you can do something like: cout << myobject; -- and have myobject handle the output. Is there a way to... echo myobject; -- and be able to have a custom definded method in
19
2363
by: McKirahan | last post by:
I am working in two environments neither configuration of which I can change; one's my Web host the other a client. My Web host requires the use of the ".php5" extension to use PHP v5.1.4; where ".php" is used for PHP v4.3.11. My client supports PHP v5.2.0 with the ".php" extension. Is there a way to reliably determine if the ".php5" extension must be used on a server? Perhaps via a "phpinfo()" value?
0
8764
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9266
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9020
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7879
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6603
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4435
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3130
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2468
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2074
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.