Closed
Description
Description
When I try to create a new record inside a RecursiveArrayIterator Object using offsetSet method, the previously specified address reference is cancelled and I lose the connection with the object.
The following code:
<?php
use Iterator;
use Traversable;
use RecursiveArrayIterator;
use JsonSerializable;
use RecursiveIterator;
interface DataInterface extends JsonSerializable, RecursiveIterator, Iterator
{
/**
* @param mixed $data
*
* @return DataInterface
*/
public static function init(Traversable $data): DataInterface;
}
class A extends RecursiveArrayIterator implements DataInterface
{
public function __construct($data)
{
parent::__construct($data);
}
public static function init($data): DataInterface
{
return new static($data);
}
public function getCols(string $colname): array
{
return array_column($this->getArrayCopy(), $colname);
}
public function bugySetMethod($key, $value)
{
$data = &$this;
while ($data->hasChildren()) {
$data = $data->getChildren();
}
$data->offsetSet($key, $value);
}
public function jsonSerialize()
{
return $this;
}
}
$example = A::init([
'test' => [
'a' => (object)[2 => '',3 => '',4 => ''],
]
]);
$example->bugySetMethod(5, 'in here');
var_dump(json_encode($example));
// result
// string(51) "{"test":{"a":{"2":"","3":"","4":"","5":"in here"}}}"
$example = A::init([
'test' => [
'b' => [2 => '',3 => '',4 => ''],
]
]);
$example->bugySetMethod(5, 'must be here');
var_dump(json_encode($example));
// result
// string(37) "{"test":{"b":{"2":"","3":"","4":""}}}"
Resulted in this output:
string(37) "{"test":{"b":{"2":"","3":"","4":""}}}"
But I expected this output instead:
string(37) "{"test":{"b":{"2":"","3":"","4":"","5":"must be here"}}}"