考慮下面的類:重寫父類方法的更精確的類型提示?
class objectCollection implements Iterator {
private $objectArray = [];
private $position = 0;
public function __construct() {
$this->position = 0;
}
public function add($object){
if(!in_array($object, $this->objectArray))
$this->objectArray[] = $object;
return $this;
}
public function remove($object){
if(($key = array_search($object, $this->objectArray())) !== false)
unset($this->objectArray[$key]);
return $this;
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->objectArray[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->objectArray[$this->position]);
}
}
class attachmentCollection extends objectCollection {
public function add(attachment $attachment){
return parent::add($attachment);
}
public function remove(attachment $attachment){
return parent::remove($attachment);
}
}
這將產生follwing錯誤: attachmentCollection聲明:: Add()方法應與objectCollection ::添加($對象)
當你看兼容代碼,我認爲這是我想要做的很明顯。 我希望attachmentCollection
基本上與objectCollection
相同,除了可以添加(或刪除)的對象需要是attachment
的實例。
這樣做的正確方法是什麼?
儘可能我知道,PHP不支持與高級語言完成相同的方式重載...這些必須具有相同的簽名... –
哦,好的。這是一個無賴。 – minychillo