当调用父公共方法(如 __call)时触发函数
在我的问题之前说一句,我对 PHP 中的 OOP 还很陌生,我非常感谢该网站,也感谢你们所有人的阅读 - 有时回答得很漂亮(如您所见 此处 或 这里,甚至这里)并帮助我大获成功处理课程的后期(某种)改进。
我之前的所有问题今天让我想到这个:
在扩展 PDOStatement 的类中,每次调用父公共方法之一时如何触发默认操作?
我可以这样做:
class genc_query extends PDOStatement{
public function rowCount(){
$this->myDefaultAction();
return parent::rowCount();
}
}
但是因为我需要以相同的方式更改几乎所有本地方法,我想知道是否没有办法触发像 __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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确实,情况似乎就是如此。
ReflectionMethod 可以让你改变方法的可访问性,但似乎它要么不适用于内部方法(即不是用户定义的),要么不会将公共方法设置为受保护/私有。它似乎旨在将受保护/私有方法公开。
看起来每个方法中的复制粘贴样板都是必要的。除了
__sleep
和__wakeup
之外,只有大约三打方法,因此只需要几分钟。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.为了代码清晰,扩展每个你想要有额外行为的方法(意味着:覆盖并调用
parent::method()
)。否则有一天,您或其他人可能会对那里发生的事情感到非常困惑。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.