Say I have an abstract class Entity, I also have a handful of abstract classes Provider, Model, Service,... all extending directly Entity. Finally, i have a last set of concrete classes ConcreteProvider, ConcreteModel, ... that extends respectively Provider, Model, ...
On each instance of Concrete* I want a method getId() that when called on an instance of a class which extends Provider ( like ConcreteProvider ), it returns the string 'Provider', and so on for Model and ...
The only way I found to achieve that is :
abstract class Entity {
abstract function getId ();
}
abstract class Provider extends Entity {
function getId () {
return __CLASS__;
}
}
abstract class Model extends Entity {
function getId () {
return __CLASS__;
}
}
class ConcreteProvider extends Provider {
}
class ConcreteModel extends Model {
}
$cp = new ConcreteProvider();
echo $cp->getId() . "\n"; // returns the string Provider
$cm = new ConcreteModel();
echo $cm->getId(); // returns the string Model
Code duplication is here obvious. I'm looking for the same behaviour without duplicate. I guess it would be nice to put the method into Entity.
Have you an idea ? How would you do that ?
// Edit
Of course, there is a way to move getId into Entity :
abstract class Entity {
function getId () {
$class = get_called_class();
while ( __CLASS__ !== get_parent_class($class) )
$class = get_parent_class($class);
return $class;
}
}
But there is a lot of computation for, imo, nothing worth...