PHP Classes

Adding methods to existing objects

Recommend this page to a friend!

      PHP Classes blog  >  Should PHP be Copying...  >  All threads  >  Adding methods to existing objects  >  (Un) Subscribe thread alerts  
Subject:Adding methods to existing objects
Summary:I really want the ability to add methods to objects.
Author:troy knapp
Date:2012-11-12 19:17:25
Update:2012-11-13 02:07:39

  1. Adding methods to existing objects   Reply   Report abuse  
Picture of troy knapp troy knapp - 2012-11-12 20:34:33
I heard what Micheal was saying @ around 26minutes about adding a method to an existing object, and it's something that I've wanted for at least a year.

I've never used Groovy or any other language that allowed for this type of dynamic scripting, but I've wanted it many times. I looked for good methods to add methods to existing classes, and couldn't find one... other then by modifying the existing code that instantiates the object.

My most simple use case that I've ran into occurs when I'm using an open source CMS, that is still live and being developed. I have, wanted to be able to add methods to core classes to add functionality without having to worry about my changes being written over when I upgrade. Ideally, just changing the core would be the best option, but I don't want my code to disappear after an update.

Another use case that I've wanted it for in the past is when I want to switch my site into a development mode and load in logging and tracing methods, but I don't want all that extra overhead in a, normal, production environment.

Just my two cents... when I heard Micheal talking about it I thought to myself "I'm not crazy!"

  2. Re: Adding methods to existing objects   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2012-11-12 22:30:40 - In reply to message 1 from troy knapp
I suspected you can do already that. I just checked it out and it seems you can do that with Closures. It is not an elegant solution but it seems to do what you want.

  3. Re: Adding methods to existing objects   Reply   Report abuse  
Picture of michael kimsal michael kimsal - 2012-11-13 02:07:39 - In reply to message 1 from troy knapp
Hey Troy:

Thanks for the reply - yes, we're both not crazy. I suspect PHP will at some point add the ability to do this, and probably manage to work the \ character in there to make that happen.

$myClass->newMethod\= function($p) { echo $p; };

or something crazy like that.

I'd encourage you to try out Groovy and perhaps Ruby or some other language that supports this to try it out. You'll get excited, then bored, then it'll fit naturally in to some of the projects you do, but you won't overuse it all the time. :)

Ping me at if you want to chat more about groovy!

For more information send a message to info at phpclasses dot org.