我是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类的对象。为什么不创建Honda类型的对象,因为返回类型是本田类型的对象?是因为我正在使用构造函数吗?
但是,如果我在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
答案 0 :(得分:3)
abstract class Car {
public static function createCar(){
try
{
// PHP 5.3+ support
return new static;
}
catch (Exception $e)
{
// in case child does not exists
}
}
}
class Honda extends Car {
}
$honda = Honda::createCar();
var_dump($honda);
答案 1 :(得分:1)
构造函数无法返回值。他们可以只创建一个放在其中的类的对象。您可以将第二个代码缩短为:
// Actually you don't need to create a new factory if your creation method is static
$Honda = $carFactory::createCar(CarFactory::HONDA);
答案 2 :(得分:0)
在构造函数中,您尝试返回新车的实例。构造函数不返回任何值,但在创建对象期间调用。 PHP确保new
关键字始终返回构造类的实例。
由于CreateCar
是静态的,因此调用应如下所示:
$carFactory = new CarFactory();
// Now create a Car
$Honda = $carFactory::createCar(CarFactory::HONDA);
var_dump($Honda);
答案 3 :(得分:0)
您需要做的是直接使用静态类方法而不启动对象($ carFactory):
$honda = CarFactory::createCar(CarFactory::HONDA);