Answer the question
In order to leave comments, you need to log in
What is the best way to implement bird class hierarchy and fly method?
Hi
I ran into a problem how to correctly implement the bird class family, the problem is with the chicken class, because they can’t fly, but why not implement the fly method separately in each class? And
abstract class Bird
{
abstract public function fly();
}
class Eagle extends Bird
{
public function fly()
{
echo "I can fly";
}
}
class Chicken extends Bird
{
public function fly()
{
// What to do here ?
die('I cant fly Error');
}
}
$birds = [new Eagle(), new Chicken(), new Eagle()];
foreach ($birds as $bird) {
echo $bird->fly();
}
Answer the question
In order to leave comments, you need to log in
The interface is just such a case.
Anyone who can fly should implement the IFlyable interface.
Option 1.
Bird:
public function fly() { echo 'I can fly', PHP_EOL; }
public function fly() { echo 'I can not fly', PHP_EOL; }
public function fly() { echo 'I can fly', PHP_EOL; }
public function fly() { echo 'I can not fly', PHP_EOL; }
public function fly() { echo 'I can fly', PHP_EOL; }
public function fly() { echo 'I can not fly', PHP_EOL; }
public function fly() { echo 'I can fly', PHP_EOL; }
public function fly() { echo 'I can not fly', PHP_EOL; }
Look towards the Strategy template.
Flying is a fairly dynamic property. It can even change during the life of an object. Therefore, this property is most often more useful to take out of the object. And to assign to the "flying" field some implementation from outside.
For example
, the Swallow flies by one method. Chicks and hens to others. Etc.
Inheritance is a pretty tight link. It should be avoided. If possible.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question