You need to change code either way.
If ::giveHug
MUST be static, then you need to be able to provide the Animal
to be hugged.
So this works:
but is not so nice
interface Animal
{
public static function giveHug(Animal $animal);
}
class Dog implements Animal
{
protected $race;
public function __construct($race)
{
$this->race = $race;
}
public static function giveHug(Animal $animal)
{
return 'Kiss my friend ' . $animal->race;
}
}
$dog = new Dog('WauWau');
echo Dog::giveHug($dog) . PHP_EOL;
// Kiss my friend WauWau
This is better:
interface Animal
{
public static function getRace();
public static function giveHug(Animal $animal);
}
class Dog implements Animal
{
protected static $race;
public function __construct($race)
{
self::$race = $race;
}
public static function getRace()
{
return self::$race;
}
public static function giveHug(Animal $animal)
{
return 'Kiss my friend ' . $animal::getRace();
}
}
$dog = new Dog('WauWau');
echo Dog::giveHug($dog) . PHP_EOL;
// Kiss my friend WauWau
BUT now to the topic: does it make sense?
No.
And this is a really good example.
You do not tell a "static" animal (or dog) to give a hug.
You would want to tell a specific (object) animal to give a hug.
So this makes more sense:
interface Animal
{
public function giveHug();
}
class Dog implements Animal
{
protected $race;
public function __construct($race)
{
$this->race = $race;
}
public function giveHug()
{
return 'Kiss my friend ' . $this->race;
}
}
$dog = new Dog('WauWau');
// Note: we call $dog to give hug. So the ONE dog =)
echo $dog->giveHug() . PHP_EOL;
// Kiss my friend WauWau
EDIT: the example
$dog = new Dog('WauWau');
echo Dog::giveHug($dog) . PHP_EOL;
is more like a "Hey, all Dogs out there ... give a hug to this (Animal $dog)".
And there are cases this makes sense. But in this case - not =)