View Full Version : PHP "monkeypatching"?

30 Mar 2010, 06:39 AM

Anyone know how I can either do this or do something similar that achieves this?

I have a validation class. It contains a load of standard validation functions. This class also supports custom validation functions. This is where my problem is.

It works something like this.

Controller sends validation class the function name to use to validate a field.
Validation class creates a new instance of the controller class.
Validation class runs controller->validation_function()
Validation runs true or false.

The problem with this is that the validation class is creating an unneeded instance of the controller class.

I want to to do this.

$validation = new validation;
// Set rules
$validation->function() = $this->validation_function();

Any ideas on how to achieve this OR simply get the controller->function into the same scope as the validation class?

30 Mar 2010, 03:02 PM
Well if the controller exists in the global scope then you can always declare it "global" at the start of the function call.

Because of the monkey patching terminology, I assume you don't want to modify the controller's code? If you don't mind... then you could make the controller a singleton or you could declare the member function static.

I don't really see why you are worried about the extra object. If your really worried you can declare unset($controller) but PHP will garbage collect at the end of a function's execution anyway, at which point the extra object will be out of scope.


Was just wondering but shouldn't the controller be delegating the validation_function to the validation object, rather than the validation object requesting it from the controller? If you do it that way, then that should solve your problem. If you can't touch the original controller code, you could extend it.

Edit #2:

There seems to be a few changes to the garbage collection and an issue with objects being picked up by the garbage collector. I'll go have a look into it and report back. :)


The garbage collector definitely does the rounds at the end of a method or function call (in PHP 5.2.13). Calling unset just before the function ends would be a waste of processor time. As for the issue with objects, destroying child objects doesn't remove their parents (whether you use direct reference or inheritance). Tis Strange.