0

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?

5 Answers 5

5

With a decorator:

class MyClassDecorator
{
    protected $decoratedInstance;

    public function __construct($decoratedInstance)
    {
        $this->decoratedInstance = $decoratedInstance;
    }

    public function methodNameInOriginalClass()
    {
        $this->decoratedInstance->methodIWantToRunBefore();
        $this->decoratedInstance->methodNameInOriginalClass();
        $this->decoratedInstance->methodIWantToRunAfter();
    }

    public function __call($method, $args)
    {
        if (method_exists($this->decoratedInstance, $method)) {
            return call_user_func_array(
                array($this->decoratedInstance, $method), 
                $args
            );
        }
    }
}

The above assumes that the methods you want to call are public on the $decoratedInstance.

Sign up to request clarification or add additional context in comments.

2 Comments

works flawlessly, thank you. also adding this helps: function &__get($prop_name){ if (isset($this->originalClass->$prop_name)) { return $this->originalClass->$prop_name; } else { return false; } } :P
Absolutely yes, but for brevity's sake I skipped it.
1

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)

Comments

1

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();

Comments

1

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

Comments

1
  • 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.