V
V
vrazbros2018-03-31 18:47:28
PHP
vrazbros, 2018-03-31 18:47:28

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

3 answer(s)
T
TheLostRoot, 2018-04-01
@TheLostRoot

The interface is just such a case.
Anyone who can fly should implement the IFlyable interface.

B
Boris Korobkov, 2018-04-01
@BorisKorobkov

Option 1.
Bird:

public function fly() { echo 'I can fly', PHP_EOL;  }

Chicken:
public function fly() { echo 'I can not fly', PHP_EOL;  }

Option 2.
Eagle, Duck:
public function fly() { echo 'I can fly', PHP_EOL;  }

Chicken:
public function fly() { echo 'I can not fly', PHP_EOL;  }

Option 3.
FlyBird:
public function fly() { echo 'I can fly', PHP_EOL;  }

Eagle, Duck extends FlyBird
Chicken:
public function fly() { echo 'I can not fly', PHP_EOL;  }

Option 4.
trait FlyBird:
public function fly() { echo 'I can fly', PHP_EOL;  }

Eagle, Duck use FlyBird
Chicken:
public function fly() { echo 'I can not fly', PHP_EOL;  }

S
Sergey, 2018-04-02
@red-barbarian

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 question

Ask a Question

731 491 924 answers to any question