我是 PHP 编程新手,正在尝试做一个基本的工厂模式。我正在尝试使用方法和构造函数创建一个类实例。
$ 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);
结果是 CarFactory 类的对象。为什么它不创建本田类型的对象,因为返回类型是本田类型的对象?是因为我使用的是构造函数吗?
但是,如果我在 CarFactory 中使用如下方法,它会创建一个 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);
}
提前致谢。SV