简体   繁体   中英

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM