【问题标题】:How to modify a variable inside parent function?如何修改父函数中的变量?
【发布时间】:2012-02-06 00:14:43
【问题描述】:

我想修改 parent 的 $item,然后,让 parent 运行其余的过程。怎么做? (我不能修改父类,它会经常通过软件更新来更新。另外请注意,$item 是函数内部的变量,它不是 parent->var)

Class Parent{
     function __constructor(){....}
     function save(){
       $items = get_items($id, $this->var);
       // process the data and save
     }
}
Class Child extends Parent{
     function __constructor(){
         parent::__construct();
     }
     function save(){
     $items = get_items($id, $var)// if.. then $var=$this->var, else $var=$something_else
      // precess data and save
    }
}

【问题讨论】:

  • 这似乎是第三方 Parent 类的糟糕设计。任何解决方案都意味着代码重复或变通的解决方法,这两种方法都会在升级时出现维护问题。这是哪个包的?

标签: php class variables


【解决方案1】:
Class Parent{
    protected $items;
     function __constructor(){....}
     function save(){
       $this->items = get_items($id, $this->var);
       // process the data and save
     }
}
Class Child extends Parent{
     function __constructor(){
         parent::__construct();
     }
     function save(){
         $this->items = something_else();
        parent::save();
    }

}

【讨论】:

  • 根据设计,这可能会覆盖子方法中保存的更改。
  • $item 不是父函数的成员变量,它是父函数内部的变量。因此,在孩子中,$item 可能不会被识别为同一个 var
【解决方案2】:

将它们作为参数传递。例如

Class Parent{
     function __constructor(){....}
     function save(){
     function save($items = null){
        $items = is_null($items) ? get_items($id, $var) : $items;
        // process the data and save
     }
}
Class Child extends Parent{
     function __constructor(){
         parent::__construct();
     }
     function save($items = null){
       $items = is_null($items) ? get_items($id, $var) : $items;
        // precess data and save
     }
     return parent::save($items);
}

【讨论】:

  • 我不能修改父类,因为软件升级时会被删除。
猜你喜欢
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 2023-02-04
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多