填充php数组时的奇怪行为

时间:2018-04-28 15:35:42

标签: php arrays iterator

我创建了一个在PHP中实现Iterator的类。该课程公开"记录"属性定义为:

private $records = [];

在类的主体中,创建一个填充数组的方法:

    /**
    * Add an item to the activeRecord collection
    * @param IActiveRecord $activeRecord
    */
   public function set(IActiveRecord $activeRecord){
    echo "Add" . $activeRecord->id . " to collection<br>\n";
    $this->records[] = $activeRecord;
    echo $this . "<br>\n";
   }

语句echo $ this指的是一个使数组内容人性化的__toString()方法:

    /**
 * Humanize class
 * @return string
 */
public function __toString(): string {
    $output = "Number of activeRecords : " . $this->size() . "<br>\n";

    foreach($this as $record) {
        $output .= "id : " . $record->id . "<br>\n";
    }

    return $output;
}

当我从查询结果中填充集合时,我得到了:

Add 1 to collection<br>
Number of activeRecords : 1<br>
id : 1<br>
<br>
Add 2 to collection<br>
Number of activeRecords : 2<br>
id : 2<br>
id : 2<br>
<br>

如您所见,第一次迭代填充id = 1,但第二次迭代添加id = 2并将第一个元素替换为id = 2 ...

我不知道这种奇怪的行为......迭代器方法正确实现(我认为):

    /**
 *
 * {@inheritDoc}
 * @see Iterator::current()
 */
public function current(){
    return $this->records[$this->index];
}

/**
 * {@inheritDoc}
 * @see Iterator::next()
 */
public function next() {
    $this->index++;
}

/**
 * {@inheritDoc}
 * @see Iterator::key()
 */
public function key(){
    return $this->index;
}

/**
 * {@inheritDoc}
 * @see Iterator::valid()
 */
public function valid(){
    return $this->index < count($this->records) ? true : false;
}

/**
 * {@inheritDoc}
 * @see Iterator::rewind()
 */
public function rewind(){
    $this->index = 0;
}

编辑1: activeRecord是来自Controller的对象:

    /**
 *
 * {@inheritDoc}
 * @see \wp\Database\SQL\Select::selectBy()
 */
public function selectBy(){

    $this->statement = $this->entity->selectBy();

    if ($this->statement !== false){
        $this->statement->setFetchMode(\PDO::FETCH_OBJ);
        while($data = $this->statement->fetch()){
            $record = $this->entity->getActiveRecordInstance();
            $record->hydrate($data);
            $this->activeRecords->set($record);
        }
        return true;
    }

    return false;
}

在这种方法中,$ this-&gt; entity-&gt; getActiveRecordInstance()是:

    /**
 * Return new ActiveRecord instance
 * @return \App\Entities\Promoteurs\PromoteursActiveRecord
 */
public function getActiveRecordInstance(){
    return new ActiveRecord($this->columns);    
}

所以,我确信每次迭代填充的ActiveRecord都是一个新对象。

0 个答案:

没有答案