I have created simple class inheritance of an abstract class Pet
which is basically the skeleton of all other children classes.
abstract class Pet {
private static $relations = array(
'Cat',
'Dog'
);
public static final function getClassById($id){
return self::$relations[$id];
}
protected static $foods = array(
);
public static function getEdibleFoods(){
$class = get_called_class();
return $class::$foods;
}
abstract public function play();
abstract public function eat();
abstract public function sleep();
}
Then I have the Dog
and Cat
classes
class Dog extends Pet {
protected static $foods = array(
'bones'
);
public function eat() { }
public function play() { }
public function sleep() { }
}
class Cat extends Pet {
protected static $foods = array(
'fish'
);
public function eat() { }
public function play() { }
public function sleep() { }
}
As you see, the only difference between them is the foods that they like. My concern about this code is the getEdibleFoods
static method in the parent class.
public static function getEdibleFoods(){
$class = get_called_class();
return $class::$foods;
}
In order to not have to implement it in all children classes, I figured I can use get_called_class()
instead of self
to return the foods
static variable. Notice that every child class has its own foods
array and they are not all the same.
My problem is that this does not look like clean code. I'd like to ask if this is good practice and if not, how is it done the right way?