0

我有以下数组:

$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 是空的。

谁能告诉我为什么?

4

2 回答 2

0

new zone($newZoneSub, '')- 你在这里传递一个字符串,但第二个参数必须是一个数组,否则你会因为参数提示而得到一个可捕获的致命错误__construct($newZoneId, array $newZoneSubs)

试试看

foreach($newZoneSubs as $newZoneSub) {
    $this->zoneSubs[] = new zone($newZoneSub, array());
}

例如

<?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
于 2013-03-07T09:51:56.620 回答
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
    }
}
于 2013-03-07T10:03:15.173 回答