在PHP中使用命名空间和依赖注入的意外行为

时间:2015-09-04 10:06:14

标签: php dependency-injection namespaces

我是新的在PHP中使用命名空间和依赖注入。我有一个简单的代码:

身体等级

<?php namespace Libraries\Models;

class Body {

  private $brand;

  public function __construct()
  {

  }

  public function getBrand()
  {
    return $this->brand;
  }

  public function setBrand($brand)
  {
    $this->brand = $brand;
  }
}

引擎类

<?php namespace Libraries\Models;

class Engine {

  private $brand = '';
  private $hp = '';

  public function __construct()
  {

  }

  public function getBrand()
  {
    return $this->brand;
  }

  public function setBrand($brand)
  {
    $this->brand = $brand;
  }

  public function getHp()
  {
    return $this->hp;
  }

  public function setHp($hp)
  {
    $this->hp = $hp;
  }
}

车级

<?php namespace Libraries\Models;

class Car {

  private $engine;
  private $body;

  public function __construct(Engine $engine, Body $body)
  {
    $this->engine = $engine;
    $this->body = $body;
  }
}

如您所见,只是一辆车可能有不同的车身和发动机。好吧,我使用这段代码来测试它是如何工作的:

test.php的

<?php
require 'models/Car.php';
require 'models/Engine.php';
require 'models/Body.php';

$engine = new Libraries\Models\Engine();
$body = new Libraries\Models\Body();

$engine->setBrand('Renault');
$engine->setHp(750);
$body->setBrand('RedBull');
$redbull = new Libraries\Models\Car($engine, $body);

$engine->setBrand('Ferrari');
$engine->setHp(800);
$body->setBrand('Ferrari');
$ferrari = new Libraries\Models\Car($engine, $body);

echo '<pre>', print_r($redbull), '</pre>';
echo '<pre>', print_r($ferrari), '</pre>';

结果是$redbull$ferrari汽车都有相同的身体和引擎,这不是我的预期。

Libraries\Models\Car Object
(
    [engine:Libraries\Models\Car:private] => Libraries\Models\Engine Object
        (
            [brand:Libraries\Models\Engine:private] => Ferrari
            [hp:Libraries\Models\Engine:private] => 800
        )

    [body:Libraries\Models\Car:private] => Libraries\Models\Body Object
        (
            [brand:Libraries\Models\Body:private] => Ferrari
        )

)

Libraries\Models\Car Object
(
    [engine:Libraries\Models\Car:private] => Libraries\Models\Engine Object
        (
            [brand:Libraries\Models\Engine:private] => Ferrari
            [hp:Libraries\Models\Engine:private] => 800
        )

    [body:Libraries\Models\Car:private] => Libraries\Models\Body Object
        (
            [brand:Libraries\Models\Body:private] => Ferrari
        )

)

我是否必须为我想要创建的每辆车创建新的车身和引擎?

谢谢!

1 个答案:

答案 0 :(得分:1)

它不是命名空间问题

您必须第二次构建引擎对象和正文对象

$engine = new Libraries\Models\Engine();
$body = new Libraries\Models\Body();

$engine->setBrand('Renault');
$engine->setHp(750);
$body->setBrand('RedBull');
$redbull = new Libraries\Models\Car($engine, $body);

$engine = new Libraries\Models\Engine();
$body = new Libraries\Models\Body();

$engine->setBrand('Ferrari');
$engine->setHp(800);
$body->setBrand('Ferrari');
$ferrari = new Libraries\Models\Car($engine, $body);