我有以下数组:
$allZones = array (
'header' => array('div1', 'div2'),
'content' => array('div3', 'div4')
);
我正在使用它以下列方式创建实例:
foreach($allZones as $newZoneId => $newZoneSubs) {
$newZone = new zone($newZoneId, $newZoneSubs);
}
'zone'类的构造函数如下所示:
public function __construct($newZoneId, array $newZoneSubs) {
$this->zoneId = $newZoneId;
if(is_array($newZoneSubs)) {
foreach($newZoneSubs as $newZoneSub) {
$this->zoneSubs[] = new zone($newZoneSub, '');
}
}
else {
echo "1: " . $newZoneSubs;
}
}
由于某种原因,$ newZoneSubs为空。
谁能告诉我为什么?
答案 0 :(得分:0)
new zone($newZoneSub, '')
- 你在这里传递一个字符串,但是第二个参数必须是一个数组,否则你会因为参数提示__construct($newZoneId, array $newZoneSubs)
而得到一个可捕获的致命错误
尝试
foreach($newZoneSubs as $newZoneSub) {
$this->zoneSubs[] = new zone($newZoneSub, array());
}
e.g。
<?php
$allZones = array (
'header' => array('div1', 'div2'),
'content' => array('div3', 'div4')
);
foreach($allZones as $newZoneId => $newZoneSubs) {
$newZone = new zone($newZoneId, $newZoneSubs);
echo $newZone, "\n";
}
class zone {
protected $zoneId, $zoneSubs;
public function __construct($newZoneId, array $newZoneSubs) {
$this->zoneId = $newZoneId;
$this->zoneSubs = array();
foreach($newZoneSubs as $newZoneSub) {
$this->zoneSubs[] = new zone($newZoneSub, array());
}
}
public function __toString() {
return $this->foo(0);
}
protected function foo($n) {
$rv = str_repeat(' ', $n)
.'zoneid='
.$this->zoneId
."\n";
foreach( $this->zoneSubs as $sub ) {
$rv .= $sub->foo($n+1);
}
return $rv;
}
}
打印
zoneid=header
zoneid=div1
zoneid=div2
zoneid=content
zoneid=div3
zoneid=div4
答案 1 :(得分:0)
问题出在你的构造函数中;如果$newZoneSubs
是可选的,您可以这样定义:
public function __construct($newZoneId, array $newZoneSubs = array())
{
$this->zoneId = $newZoneId;
foreach($newZoneSubs as $newZoneSub) {
$this->zoneSubs[] = new zone($newZoneSub);
// ^^
// not passing the second param
}
}