我仍在学习理解 ZF2,恕我直言,最好的方法是做事。我遇到了这个奇怪的问题,想知道这是否是预期的行为。
在我的应用程序中,我有以下代码
//In module.php getServiceConfig()
return array(
'invokables' => array(
'hardwareEntity' => 'Hardware\Model\Hardware',
),
}
在我的控制器中,我从一团文本中检索数据,这会导致 x 元素数组让我们以 3 为例
$hardwares = array(
'hw1' => array(
'name' => 'router1'
'ip' => '192.168.0.200',
'type' => 'router',
),
'hw2' => array(
'name' => 'pc1'
'ip' => '192.168.0.210',
'type' => 'pc',
),
'hw3' => array(
'name' => 'pc2'
'ip' => '192.168.0.211',
'type' => 'pc',
),
);
我在硬件模块中有一个硬件类
namespace Hardware\Model\;
class Hardware
{
protected $name = null;
protected $ip = null;
protected $type = null;
public function exchangeArray(array $data) {
$this->name = (isset($data['name'])) ? $data['name'] : $this->name;
$this->ip = (isset($data['ip'])) ? $data['ip'] : $this->ip;
$this->type = (isset($data['type'])) ? $data['type'] : $this->type;
}
}
好的,当我执行以下 foreach 循环时,魔法就来了,我得到了不同的结果
foreach($hardwares as $hw) {
$h = $this->getServiceManager()->get('hardwareEntity');
$h->exchangeData($hw);
$aObjects[] = $h
}
$aObjects 数组现在包含 3 个元素,其对象类型为 Hardware\Model\Hardware,但包含最后一个 $hardwares 元素的数据(也就是在循环时用数据覆盖所有类)
结果:
array(3) {
[0]=>
object(Hardware\Model\Hardware)#219 {
["name":protected]=>
string(7) "pc2"
["ip":protected]=>
string(13) "192.168.0.211"
["type":protected]=>
string(6) "pc"
}
[1]=>
object(Hardware\Model\Hardware)#219 {
["name":protected]=>
string(7) "pc2"
["ip":protected]=>
string(13) "192.168.0.211"
["type":protected]=>
string(6) "pc"
}
[2]=>
object(Hardware\Model\Hardware)#219 {
["name":protected]=>
string(7) "pc2"
["ip":protected]=>
string(13) "192.168.0.211"
["type":protected]=>
string(6) "pc"
}
但是当我这样做时
foreach($hardwares as $hw) {
$h = new \Hardware\Model\Hardware();
$h->exchangeData($hw);
$aObjects[] = $h
}
它用新实例化的类填充 $aObjects 数组,每个类包含不同的数据。
结果:
array(3) {
[0]=>
object(Hardware\Model\Hardware)#219 {
["name":protected]=>
string(7) "router1"
["ip":protected]=>
string(13) "192.168.0.200"
["type":protected]=>
string(6) "router"
}
[1]=>
object(Hardware\Model\Hardware)#220 {
["name":protected]=>
string(7) "pc1"
["ip":protected]=>
string(13) "192.168.0.210"
["type":protected]=>
string(6) "pc"
}
[2]=>
object(Hardware\Model\Hardware)#221 {
["name":protected]=>
string(7) "pc2"
["ip":protected]=>
string(13) "192.168.0.211"
["type":protected]=>
string(6) "pc"
}