Answer the question
In order to leave comments, you need to log in
What's wrong (polymorphism)?
Recently I went to an interview and they asked me to tell you what polymorphism is.
Answered the following.
class unit {
public $hp = 'NaN';
public function setHp (){
return $this->hp = "30 hp";
}
}
class warrior extends unit {
public function setHp (){
return $this->hp = "80 hp";
}
}
class medic extends unit {
public function setHp (){
return $this->hp = "40 hp";
}
}
class tank extends unit {
public function setHp (){
return $this->hp = "200 hp";
}
}
$warrior = new warrior;
$medic = new medic;
$tank = new tank;
$unit = new unit;
echo $warrior->setHp();
echo $medic->setHp();
echo $tank->setHp();
echo $unit->setHp();
Answer the question
In order to leave comments, you need to log in
There are several different kinds of polymorphism in programming. You should have specified which one you are talking about. Of course, the interviewer with you is not entirely correct, since the simplest form of polymorphism is still present in your example. Another thing is that in php polymorphism is usually understood as polymorphism of subtypes. Looks like that
interface UnitInterface {
public function setHp();
}
class Warrior implements UnitInterface {
public function setHp() {...}
}
class Medic implements UnitInterface {
public function setHp() {...}
}
class MainProgram {
private $unit;
public function __construct(UnitInterface $unit) {
$this->unit = $unit;
}
public function run() {
return $this->unit->setHp();
}
}
echo (new MainProgram(new Warrior())->run();
Maybe it was worth making the method abstract in unit, and then overriding it? Because we do not use the unit separately, so we do not need to know the implementation of the function for it. You only need to know if the function exists.
return $this->hp = "200 hp";
The design is something unknown to the world.
Why is return everywhere?
Why does an assignment return?
Well, it's probably more logical to do a unit interface, and not a class.
If parametric polymorphism was assumed in the question, then it should have been shown. You have shown only inheritance and creation of objects. It was necessary to at least drive them into an array and do setHp () in a cycle. Thus, to show that it doesn’t matter what type it is. unit can be replaced with an interface, and make some external function that would require this interface, and you would pass warriors and tanks there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question