<?php
class AnimalFood
{
public function prepare(): string
{
return 'Prepare animal food.'."\n";
}
}
class PetFood extends AnimalFood
{
public function prepare(): string
{
return 'Prepare pet food.'."\n";
}
public function getProducer(): string
{
return 'PetFruitLTD.';
}
}
class Animal
{
public function feed(AnimalFood $food): Animal
{
echo $food->prepare();
echo 'Feeding...'."\n";
return $this;
}
}
class Pet extends Animal
{
public function feed(AnimalFood $inputFood): Pet
{
$food = $this->getFood($inputFood);
parent::feed($food);
echo sprintf('Producer of pet food was %s'."\n", $food->getProducer());
return $this;
}
private function getFood(AnimalFood $food): PetFood
{
return $food;
}
}
$pet = new Pet();
$petFood = new PetFood();
$pet->feed($petFood);
/**
Prepare pet food.
Feeding...
Producer of pet food was PetFruitLTD.
*/
Of course the title question corresponds to the getFood
method in class Pet
. I don't know is it correct to achieve that result that when I get in argument of base class (method getFood
in Pet
), then I invoke method to get correct type. Type where I will know that it has method I'am looking for. This is not a abuse of LSP? I ask because it is the only one way I know which can make static analysis makes possible to pass eg. in VSCode.
Perhaps there other workarounds? Please help.