PHP棘手问题
我有以下类结构:
class Parent
{
public function process($action)
{
// i.e. processCreateMyEntity
$this->{'process' . $action};
}
}
class Child extends Parent
{
protected function processCreateMyEntity
{
echo 'kiss my indecisive ass';
}
}
我需要在 Child 类中编写一些统一的方法来处理几个非常相似的创建实体的操作。我无法更改 Parent::process 并且我需要从中调用这些方法。
首先想到的是神奇的 __call 方法。实体名称是从第一个 __call 参数解析的。所以结构变成:
class Parent
{
public function process($action)
{
// i.e. processCreateMyEntity
$this->{'process' . $action};
}
}
class Child extends Parent
{
protected function __call($methodName, $args)
{
$entityName = $this->parseEntityNameFromMethodCalled($methodName);
// some actions common for a lot of entities
}
}
但问题是 __call 不能像我需要的那样受到保护。我在 __call 方法的开头放置了一个 hack 方法调用,该方法通过 debug_backtrace 检查该方法是否在 Parent::process 内部调用,但这闻起来很糟糕。
有什么想法吗?
I have the following class structure:
class Parent
{
public function process($action)
{
// i.e. processCreateMyEntity
$this->{'process' . $action};
}
}
class Child extends Parent
{
protected function processCreateMyEntity
{
echo 'kiss my indecisive ass';
}
}
I need to write some unified method in Child class to process several very similar actions for creating entities. I can't change the Parent::process and I need those methods to be called from it.
The first thing that comes to mind is magic __call method. The entity name is parsed from the first __call argument. So the structure turns to:
class Parent
{
public function process($action)
{
// i.e. processCreateMyEntity
$this->{'process' . $action};
}
}
class Child extends Parent
{
protected function __call($methodName, $args)
{
$entityName = $this->parseEntityNameFromMethodCalled($methodName);
// some actions common for a lot of entities
}
}
But the thing is that __call can't be protected as I need it. I put a hack method call at the beginning of __call method that checks via debug_backtrace that this method was called inside Parent::process, but this smells bad.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果“几个”意味着 3 或 4,我可能会这样做:
当然,有重复的代码,但它所做的立即有意义。有一些函数可以做类似的事情,而且很容易发现这一点。
If 'several' means 3 or 4, I'd probably just do something like:
Sure, there is duplicate code, but what it does makes immediate sense. There are a handful of functions that do something similar, and it's easy to discover that.
我假设你的孩子是从父母那里延伸出来的。
那么你可以做的是:
I am assuming your child extends from the parent.
Then what you could do is:
实际上,您不需要
__call
,您可以创建自己的并受保护:根据您问题中的描述,这应该合适,但我并不完全适合当然。
Actually, you don't need
__call
, you can create your own and protected:According to the description in your question, this should be fitting, but I'm not entirely sure.