Consider the following code:
class Vehicle {
/**
* Create a new instance of Vehicle
*
* @return Vehicle
*/
public static function create(){
return eval( "return new " . get_called_class() . '();' );
// return self(); would always return Vehicle reg ardless
}
public function drive(){
echo "I am a Vehicle!";
}
}
class Bus extends Vehicle {
public function drive(){
parent::drive();
echo "\nSpecifically, a bus!";
}
}
class Car extends Vehicle {
public function drive(){
parent::drive();
echo "\nSpecifically, a car!";
}
}
// Drive a car
Car::create()->drive();
// Drive a bus
Bus::create()->drive();
I’ve implemented a factory “create” method in the Vehicle class that allows me to get an instance of the class that I want to use.
I tried using “return new self();” but that always returns an instance of Vehicle, so I resorted to using eval.
question: Is there a non-eval way to implement the create() method so that:
- it returns an instance of the class you’re using
- it doesn’t require implementing create() on each of the extending classes
Use static instead of
self, e.g.prints