I am new to PHP programming and am trying out to do a basic Factory Pattern. I am trying to create a class instance using a method and also using a constructor.
$ abstract class Car {
public $type;
public function getType(){
echo $this->type;
}
}
//Class that holds all the details on how to make a Honda.
class Honda extends Car{
public $type = "Honda";
}
class CarFactory {
const HONDA = "Honda";
public function __construct($carType){
switch($carType){
case self::HONDA:
return new Honda();
break;
}
die("Car isn't recognized.");
}
}
$Honda = new CarFactory(carFactory::HONDA);
var_dump($Honda);
The result is of an object of class CarFactory. Why doesn't it create an object of type Honda as the return type is an object of type Honda? Is is because I am using a constructor?
However, if I use a method inside CarFactory as below, it creates an object of type Honda
class CarFactory {
const HONDA = "Honda";
public static function createCar($carType){
switch($carType){
case self::HONDA:
return new Honda();
break;
}
die("Car isn't recognized.");
}
$carFactory = new CarFactory();
//Create a Car
$Honda = $carFactory->createCar(CarFactory::HONDA);
var_dump($Honda);
}
Thanks in advance. SV