By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,972 Members | 901 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,972 IT Pros & Developers. It's quick & easy.

Operator Overloading

P: n/a
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
myobject do some kind of output?

Any other suggestions?
( I was thinking of having a custom method called echo in myobject so
one could do echo myobject->echo(); This is not as clean....)

Thanks!!

Jul 14 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a

deciacco wrote:
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
myobject do some kind of output?

Any other suggestions?
( I was thinking of having a custom method called echo in myobject so
one could do echo myobject->echo(); This is not as clean....)

Thanks!!
Use the magic method __toString(). Note: it is only invoked when
directly printed. echo "$myobj" will not invoke __toString()

See http://us2.php.net/manual/en/language.oop5.php for more info about
PHP5 objects

Jul 14 '06 #2

P: n/a
deciacco wrote:
Any other suggestions?
( I was thinking of having a custom method called echo in myobject so
one could do echo myobject->echo(); This is not as clean....)

Richard is correct define a function called __toString() in your class
without whatever class variables you want to print off. Notice that
there are 2 underscores on __toString()

You might want to consider an excellent book called PHP 5 Objects,
Patterns, and Practice... I'm reading it now and it covers many of
PHP's advancent features including OO and design patterns.

~john

Jul 14 '06 #3

P: n/a
Thank you both...that's awsome...I will def look into that
book...thanks for the suggestion!!!

~john wrote:
deciacco wrote:
Any other suggestions?
( I was thinking of having a custom method called echo in myobject so
one could do echo myobject->echo(); This is not as clean....)


Richard is correct define a function called __toString() in your class
without whatever class variables you want to print off. Notice that
there are 2 underscores on __toString()

You might want to consider an excellent book called PHP 5 Objects,
Patterns, and Practice... I'm reading it now and it covers many of
PHP's advancent features including OO and design patterns.

~john
Jul 15 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.