{a:'A', b:'B'}
我希望它像
{a:'A', new_a:'A', b:'B', new_b:'B'}
使用的代码是:
<?PHP
$obj = new stdClass();
$obj->a = 'A';
$obj->b = 'B';
foreach($obj as $field=>$value)
{
$obj->{'new_'.$field} = $value;
}
输出是:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 21290 bytes) in /path/to on line 9
第9行是这样的:
$obj->{'new_'.$field} = $value
我确实有其他方法可以解决问题,但我不明白为什么这个特定的代码会产生这个错误.
有没有人知道这个错误的原因,最终解释.
谢谢!
解决方法:
问题是,当您迭代源对象属性时,您将向源对象添加更多属性,因此foreach循环永远不会结束.
foreach ($obj as $field => $value)
{
$obj->{'new_'.$field} = $value;
var_dump($obj);
}
结果是:
object(stdClass)#1 (29) {
["a"]=>
string(1) "A"
["b"]=>
string(1) "B"
["new_a"]=>
string(1) "A"
["new_b"]=>
string(1) "B"
["new_new_a"]=>
string(1) "A"
["new_new_b"]=>
string(1) "B"
["new_new_new_a"]=>
...
相反,创建一个新对象并替换旧对象:
$obj = new stdClass();
$obj->a = 'A';
$obj->b = 'B';
$newObj = new stdClass();
// copy old properties
foreach ($obj as $field => $value) {
$newObj->{$field} = $value;
}
// Create new properties
foreach($obj as $field => $value) {
$newObj->{'new_' . $field} = $value;
}
甚至:
$obj = new stdClass();
$obj->a = 'A';
$obj->b = 'B';
$newObj = new stdClass();
// copy old properties and create new
foreach ($obj as $field => $value) {
$newObj->{$field} = $value;
$newObj->{'new_' . $field} = $value;
}