views:

212

answers:

5

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?

+1  A: 

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)

soulmerge
+1  A: 

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();
Stephen Melrose
+1  A: 

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

Emil Ivanov
+1  A: 
  • runkit: Replace, rename, and remove user defined functions and classes.
  • funcall: Call callbacks before or after specified functions/methods being called.
  • intercept: Allows the user to have a user-space function called when the specified function or method is called.

not that using these is necessarily a good idea.

just somebody
+2  A: 

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);
        }
    }
}
Gordon
works flawlessly, thank you.also adding this helps: function } else { return false; } }:P
YuriKolovsky
Absolutely yes, but for brevity's sake I skipped it.
Gordon