2

我是 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

4

4 回答 4

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);
于 2012-12-17T05:46:25.043 回答
1

构造函数不能返回值。他们可以只创建他们所在的类的对象。您可以像这样使您的第二个代码更短:

// Actually you don't need to create a new factory if your creation method is static
$Honda = $carFactory::createCar(CarFactory::HONDA);
于 2013-02-09T07:25:02.333 回答
0

在您的构造函数中,您尝试返回一辆新车的实例。构造函数不返回任何值,而是在创建对象期间调用。PHP 确保new关键字总是返回构造类的实例。

因为CreateCar是静态的,所以调用应该是这样的:

$carFactory = new CarFactory();

// Now create a Car
$Honda = $carFactory::createCar(CarFactory::HONDA);
var_dump($Honda); 
于 2012-09-11T06:50:36.360 回答
0

您需要做的是直接使用静态类方法而不启动对象($carFactory):

$honda = CarFactory::createCar(CarFactory::HONDA);
于 2018-05-02T19:34:24.097 回答