PHP棘手的问题

时间:2011-09-26 20:00:05

标签: php class-hierarchy

我有以下类结构:

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中调用的,但这闻起来很糟糕。

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

我假设您的孩子从父母延伸。

然后你可以做的是:

public function process($action)
{
    $methods = get_class_methods($this);
    $action = 'process' . $action;
    if(in_array($action, $methods)){
        $this->{$action}()
    }
    else {
       die("ERROR! $action doesn't exist!");
    }
}

答案 1 :(得分:2)

如果'几个'意味着3或4,我可能会做类似的事情:

protected function processThis()
{
  return $this->processThings();
}

protected function processThat()
{
  return $this->processThings();
}

protected function processThings()
{
  //common function
}

当然,有重复的代码,但它的作用立竿见影。有一些功能可以做类似的事情,而且很容易发现它。

答案 2 :(得分:0)

实际上,您不需要__call,您可以创建自己的和受保护的:

class Parent
{
    public function process($action)
    {
        // i.e. processCreateMyEntity
        $this->entityCall('process' . $action);
    }
}

class Child extends Parent
{
    protected function entityCall($methodName, $args)
    {
        $entityName = $this->parseEntityNameFromMethodCalled($methodName);
        // some actions common for a lot of entities
    }
}

根据你问题中的描述,这个应该适合,但我不完全确定。

相关问题