473,387 Members | 1,573 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 "overloading"
(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 "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

--- 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 4684
["Followup-To:" header set to comp.lang.php.]
On 2005-01-22, Terje Slettebų <ts*******@hotmail.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 "overloading" 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.sourceforge.net> wrote in message
news:35*************@individual.net...
["Followup-To:" header set to comp.lang.php.]
On 2005-01-22, Terje Slettebų <ts*******@hotmail.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 "overloading" 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 someOverloadedFun()
{
$numargs = func_num_args();
$args = func_get_args();
if (0 == $numargs) {
return "ERROR!";
}
if (1 == $numargs) {
if (is_string($args[0])) {
return "Received string: $args[0]";
} elseif (is_object($args[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*******@hotmail.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********************@comcast.com...
"Terje Slettebų" <ts*******@hotmail.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 "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").
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*******@hotmail.com> wrote in message
news:41******@news.broadpark.no...

I hardly think what PHP describes as "overloading"
(__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+$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).

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


In some cases you can solve such issues with interfaces.

Micha
Jul 17 '05 #8
"Michael Fesser" <ne*****@gmx.net> wrote in message
news:e6********************************@4ax.com...
.oO(Terje Slettebų)
No way to implement "$object+$object", 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.net> wrote in message
news:9m********************************@4ax.com...
.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
"Terje Slettebų" <ts*******@hotmail.com> wrote in message
news:41******@news.broadpark.no...
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").
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.
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.
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.
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.


By golly I could be done in C++. I would have sworn that it can't be. Must
have gotten it confused with Javascript.
Jul 17 '05 #11
Chung Leong wrote:
"Terje Slettebų" <ts*******@hotmail.com> wrote in message
news:41******@news.broadpark.no...
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.
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;
}
}


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.)
Make it easier to share code behind the different types too.


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

Jul 17 '05 #12
Terje Slettebų wrote:
"Chung Leong" <ch***********@hotmail.com> wrote in message
news:LK********************@comcast.com...
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) { ... }


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.

Berislav
Jul 17 '05 #13
(Changing thread only to comp.lang.php)

"Berislav Lopac" <be************@lopsica.com> wrote in message
news:ct**********@garrison.globalnet.hr...
Terje Slettebų wrote:
"Chung Leong" <ch***********@hotmail.com> wrote in message
news:LK********************@comcast.com...
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) { ... }


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


Function overloading is still one kind of overloading, so your correction is
incorrect. :)
Overload, in its most general sense, is when a unit, depending on the
circumstances, does different things.
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.
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.
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;

etc.
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.
Indeed.
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.
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?
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.
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".
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.
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++).
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
}
}


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) :
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
Jul 17 '05 #14
On Wed, 26 Jan 2005 00:49:40 +0100, "Terje Slettebų"
<ts*******@hotmail.com> wrote:
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.


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,
$arugments)
}
}

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

Jul 17 '05 #15
"Terje Slettebų" <ts*******@hotmail.com> wrote in message
news:11*********************@z14g2000cwz.googlegr oups.com...
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.


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.
Jul 17 '05 #16
Terje Slettebų scribbled something along the lines of:
"Michael Fesser" <ne*****@gmx.net> wrote in message
news:e6********************************@4ax.com...
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).


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.

--
Ashmo
Jul 17 '05 #17
Chung Leong wrote:
"Terje Slettebų" <ts*******@hotmail.com> wrote in message
news:11*********************@z14g2000cwz.googlegr oups.com...
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.
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.
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.
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.


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

Regards,

Terje

Jul 17 '05 #18

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

Similar topics

8
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...
0
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...
11
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....
4
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...
0
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...
5
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...
4
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
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...
19
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...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.