PHP: run function when a specific class method is run
what I want is to run some additional functions when a class method is run without altering the already existing class.
how?
PHP: run function when a specific class method is run
what I want is to run some additional functions when a class method is run without altering the already existing class.
how?
That is not possible, you will have to alter the function to achieve that. But you might be in need of an observer pattern (The zend guys describe the observer pattern on zend.com, too)
Your best bet is to extend the original class and override the method adding your code.
class MyClass extends OriginalClass
{
public function originalMethod()
{
parent::originalMethod();
// My code...
}
}
$myClass = new MyClass();
$myClass->originalMethod();
What you are trying to do is called Aspect Oriented Programming.
Currently PHP has not support for that out of the box, although you can use extensions. Here is post that explains some of the options: http://sebastian-bergmann.de/archives/573-Current-State-of-AOP-for-PHP.html
not that using these is necessarily a good idea.
With a decorator:
class MyClassDecorator
{
protected $originalClass;
public function __construct($originalClass)
{
$this->originalClass = $originalClass;
}
public function methodNameInOriginalClass()
{
$this->originalClass->methodIWantToRunBefore();
$this->originalClass->methodNameInOriginalClass();
$this->originalClass->methodIWantToRunAfter();
}
public function __call($method, $args)
{
if(method_exists($this->originalClass, $method)) {
return call_user_func_array(array($this->originalClass,
$method), $args);
}
}
}