James P.
James P.

Reputation: 19607

Call method in abstract class after method of extending class?

Say I have a class called MyClass which extends MyAbstractClass.

Within MyClass there is myMethod. Within MyAbstractClass there is myAsbtractClassMethod.

Is there a way I could have myAsbtractMethod called when myMethod is finished without having to place parent::myAsbtractClassMethod at the end ?

Upvotes: 1

Views: 130

Answers (1)

Ashley Bickerstaff
Ashley Bickerstaff

Reputation: 193

No there isn't I'm afraid.

If you're hoping to achieve 'post execution hook' style functionality, you could design your class to implement the __call() magic method. For example:

<?php

abstract class AbstractTest
{
  protected function myMethod()
  {
    echo 'Bar';
  }
}

class Test extends AbstractTest
{

  public function __call($methodName, $args)
  {
    call_user_func_array(array($this, $methodName), $args);
    call_user_func_array(array('parent', $methodName), $args);
  }

  protected function myMethod()
  {
    echo 'Foo';
  }

}

$test = new Test();

// Will output 'FooBar'
$test->myMethod();

By declaring myMethod() to be protected, you can't call it publicly. It therefore gets 'intercepted' by __call() method which calls it in it's own context and then that of its' parent. This may require a redesign of how your classes are built though.

Upvotes: 1

Related Questions