Welcome Guest, Not a member yet? Register   Sign In
Dynamically adding a function to an object
#1

[eluser]TheFuzzy0ne[/eluser]
Hi everyone.

Is there a way to dynamically add a function to an already instantiated class? I would just like to create an alias for an existing function in order to implement a fix that's planned for the library some time in the future. I read about the "Function" construct some time ago, but I can't remember where I found it in the PHP docs.

Thanks in advance.
#2

[eluser]bretticus[/eluser]
Apparently so, there are examples in the user comments for the [email=http://us2.php.net/manual/en/function.create-function.php]create_function()[/email] function Wink Apparently, they have to be anonymous functions though. Wonder if you could assign them with magic method __set() to get around that. I'd be very interested to see what you come up with.

Good luck!
#3

[eluser]sophistry[/eluser]
@LOL...

sounds to me like you need to take a step back from the problem. maybe a simple class extends class would work for you? you probably thought of that already, but maybe there is another way to get the results you desire without implementing the *exact* approach you mentioned?

:pensive:
#4

[eluser]TheFuzzy0ne[/eluser]
Hi.

I understand that there are other, possibly better methods available, but it was more a question of interest than anything else. Personally, I think it would be quite useful to be able to add or override a method this way.

I'll be able to reply in more detail another time. My XP installation is suffering from a serious case of [url="http://en.wikipedia.org/wiki/Bit_rot"]bit rot[/url] and can't see my on-board ethernet controller, so I need to do a fresh install. (Ugh!)

Thank you both for your comments.
#5

[eluser]sophistry[/eluser]
oh, i see...

are you on PHP5? is the method a setter or getter? you could use magic methods __get() and or __set()
#6

[eluser]xwero[/eluser]
in php5.3 you can use the __callStatic magic function to add methods at runtime.
#7

[eluser]TheFuzzy0ne[/eluser]
Unfortunately none of these methods worked the way I'd hoped, so it seems it's not possible to dynamically add functions to an instantiate class without extending the class, although it is possible to to add properties dynamically (as we all know).

Thanks for your replies, everyone.
#8

[eluser]sophistry[/eluser]
"add properties dynamically", hmmmmnn.... maybe you could copy objects into "dynamic" properties at runtime and then those objects would expose whatever methods they came along with.
#9

[eluser]TheFuzzy0ne[/eluser]
That would be possible, but defies the point. It's not a problem though, I was just wondering if it was possible, as it would certainly be useful.

Thanks for your comments.
#10

[eluser]sophistry[/eluser]
oh yeah. that's true. those attached objects wouldn't overload any functions for you... or would they.

Thanks for *your* comments. ;-)




Theme © iAndrew 2016 - Forum software by © MyBB