开发者

Triggering a function when a parent public method is called (like __call)

A word before my question to say I am pretty new to OOP in PHP, and I'm very grateful to the site, and you all for reading - and sometimes answering beautifully (as you can see here or here, or even here) and helping big time my late (sort of) improvement dealing with classes.

All my previous questions lead me today to this one:

In a class extending PDOStatement, how can I trigger a default action each time one of the parent public methods is called?

I can do this:

class genc_query extends PDOStatement{
  public function rowCount(开发者_运维技巧){
    $this->myDefaultAction();
    return parent::rowCount();
  }
}

But as I need to change in the same way almost all of the native methods, I wonder if there's no way to trigger a function like __call() as if these methods were private (as it's not possible to make them private).


as it's not possible to make them private

Indeed, this seems to be the case.

ReflectionMethod can let you change the accessibility of a method, but it seems that it either doesn't work on internal methods (i.e. not user-defined) or it won't set public methods to protected/private. It seems designed to make protected/private methods public instead.

It looks like your copy-and-paste boilerplate inside each method is going to be necessary. Besides __sleep and __wakeup, there are only about three dozen methods, so it should only take you a few minutes.


For the sake of clear code, extend every method (means: overwrite and call parent::method() there), that you wants to have additional behaviour. Else there will be some day, where you or someone else may get really confused on what happens there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜