Reputation: 121
I have some code below
/*abstract*/ class Animal{
protected $name;
protected $legs;
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
// abstract public function sound();
}
class Cat extends Animal{
public function sound(){
echo 'Meo meo meo';
}
}
class Crocodile extends Animal{
public function sound(){
echo 'Never hear it';
}
}
function check(Animal $a){
echo $a->getName();br();
echo $a->sound();br();
}
$cat = new Cat();
$cat->setName("Cat");
$cro = new Crocodile();
$cro->setName('Nothing');
class test{
public function check(Animal $a){
echo $a->getName();
echo $a->sound();
}
}
$t = new test();
$t->check($cro);
I think, if don't use abstract so the last line $t->check($cro) must wrong, but Why it run nice. I want ask a question, in class test with check method, $a->sound(); no exists in Animal but it still run. It run like when I open comment abstract class, both of thing is not different. I really wonder, maybe I have wrong understood this problem, twisted
Upvotes: 1
Views: 149
Reputation: 76414
We are talking about animals and specific animals, like cats and crocodiles. While in your definition the concept of animal is not related to the method of sound, specific animals, like cats and crocodiles, which are inherited from animals have the ability of sound. This is how you get from the more general to the more concrete. You will get more particularities at the end.
Your Animal
class
has a protected
$name
member along with a getter and a setter. They are useful, since you will not have to redefine these for Crocodile
or Cat
. But you could tell the Animal
class
that you do not know how the sound
method will look like at particulars, but you do know that all Animals
can make a sound
. This is why the class
is abstract
: you can implement a part of it, but some things cannot be implemented at Animal
level, as the different types of animals will have different types of sound.
Upvotes: 1