Page 1 of 1

Code to run on class loading

Posted: Tue Mar 30, 2010 6:24 pm
by phu
Hey all -
I'm a veteran PHP programmer... I'm currently looking for a way to execute code when a class is defined.

Note that this isn't the same as when an object is instantiated; I know about __construct (and have committed some fun perversions with it). I'm looking for a hook or method I can use to execute code during or immediately after actual class definition, specifically to register classes that share a parent.

I could do this with an extra call or an instantiation following every definition of a subclass, but I'm hoping to avoid that, as I'd like this to be reusable and as simple as possible from the programmer's perspective. Has anyone managed anything like this in PHP?

Thanks!

Re: Code to run on class loading

Posted: Tue Mar 30, 2010 7:03 pm
by AbraCadaver
Not knocking you, but I can't think of a single practical use for this. Really the only way I can think of is to have each class in it's on file and add the code your speaking of in the same file. Aside from that you could do it where you include the classes, like in an autoloader.

Re: Code to run on class loading

Posted: Tue Mar 30, 2010 7:44 pm
by phu
No worries; I can understand that point of view. However, many things you wouldn't do in every-day PHP code start to become interesting when you're doing things that involve, for example, registering classes with each other. It's a pretty normal feature of some other languages, so there's definitely a reasonable set of use cases for it.

While autoloading might work in some instances, I'm explicitly avoiding it for this, as I'm doing some other things that require children of certain classes to be loaded before they're used at all.

I figured out I can get around this by iterating through the defined classes after the dynamic load I'm using to grab everything... however, that's pretty ugly, so I'm still interested in whether anyone is familiar with a way to manage this in PHP.