Is there a way to get rid of the getCopy() method in the derived class HelloAndGoodbye, given that it looks the same as the getCopy() in the base class Hello?
And what is more, what is there an efficient way to achieve this?
(the only difference between the two functions is that in the baseclass 'static' refers to 'Hello' and in the derived class 'static' refers to 'HelloAndGoodbye; as for the variables contained therein they can be easily renamed so that they are the same in both functions).
<?php
class Hello {
private $hello;
public function createStub() {
return new static(null);
}
public function __construct($hello) {
$this->setHello($hello);
}
public function getCopy() {
$helloCopy = static::createStub();
$this->doCopy($helloCopy);
return $helloCopy;
}
public function doCopy($helloCopy) {
$helloCopy->setHello($this->hello);
}
public function setHello($hello) {
$this->hello = $hello;
}
public function getHello($hello) {
return $this->hello;
}
public function __toString() {
return $this->hello . "\n";
}
}
class HelloAndGoodbye extends Hello {
private $goodbye;
public function createStub() {
return new static(null, null);
}
public function __construct($hello, $goodbye) {
parent::__construct($hello);
$this->setGoodbye($goodbye);
}
public function getCopy() {
$helloAndGoodbyeCopy = static::createStub();
$this->doCopy($helloAndGoodbyeCopy);
return $helloAndGoodbyeCopy;
}
public function doCopy($helloAndGoodbyeCopy) {
parent::doCopy($helloAndGoodbyeCopy);
$helloAndGoodbyeCopy->setGoodbye($this->goodbye);
}
public function setGoodbye($goodbye) {
$this->goodbye = $goodbye;
}
public function getGoodbye($goodbye) {
return $this->goodbye;
}
public function __toString() {
return parent::__toString() . $this->goodbye . "\n";
}
}
function test() {
$hello = new Hello("Hello John");
$helloAndGoodbye = new HelloAndGoodbye("Hello Jane", "Goodbye Jane");
echo $hello;
echo $helloAndGoodbye;
}
test();
OUTPUT:
Hello John
Hello Jane
Goodbye Jane