每次调用$this->processes->data
时,$this->load_operations()
都会以某种方式扩展。我真的不明白为什么当我的代码没有明确修改该对象时,该对象也会更改。
我想念什么吗?
如果我将$process
(在foreach中)强制转换为数组,然后返回到对象$this->processes->data
,则不会扩展。
$process = (array) $process;
$process = (object) $process;
class Test_library
{
private $processes;
private $tasks;
private $operations;
public function __construct()
{
$this->processes = (object) array(
'data' => (object) array(
'3' => (object) array(
'id' => '3',
)
)
);
$this->tasks = (object) array(
'data' => (object) array(
'5' => (object) array(
'id' => '5',
'processes_id' => '3',
),
'6' => (object) array(
'id' => '6',
'processes_id' => '3',
)
)
);
$this->operations = (object) array(
'processes' => (object) array(
'3' => (object) array(
'id' => '3',
'data' => array()
)
)
);
print_r($this->processes->data);
$this->load_operations();
print_r($this->processes->data);
}
private function load_operations()
{
if(!empty($this->processes->data))
{
foreach($this->processes->data as $process)
{
$this->operations->processes->{$process->id} = $process;
}
}
if(!empty($this->tasks->data))
{
foreach($this->tasks->data as $task)
{
$this->operations->processes->{$task->processes_id}->data[] = (object) [
'machine' => [],
'task' => $task
];
}
}
}
}
new Test_Library;
两个print_r
的结果应该相同。
答案 0 :(得分:5)
您的问题是,粗略地说,对象是通过引用传递的。可以在in the documentation中找到详细信息。
在您的第一个foreach
循环中,您将对$this->processes->data->3
的引用分配给$this->operations->processes->3
foreach($this->processes->data as $process) {
$this->operations->processes->{$process->id} = $process;
}
在下一个循环中,您将附加到您刚刚建立的data
的{{1}}属性中,作为对$this->operations->processes->3
的引用。
$this->processes->data->3
要解决此问题,您可以尝试在第一个循环的赋值过程中使用 foreach($this->tasks->data as $task) {
$this->operations->processes->{$task->processes_id}->data[] = (object) [
'machine' => [],
'task' => $task
];
}
运算符(有关更多详细信息,请访问see here),也可以简单地使用关联数组。