Php 在for循环中使用stdClass()时,所有值都相同
我在下面有一个函数getComment。这个函数的问题是Php 在for循环中使用stdClass()时,所有值都相同,php,sql-server-2008,Php,Sql Server 2008,我在下面有一个函数getComment。这个函数的问题是 $test->TestComments[$type]将包含相同的值,包括最后一条注释及其用户名和时间戳 public function getComment($test) { $Id = $test->Id; $localComment = new stdClass(); $queryComment = $this->getResultCommentQuery($Id); $result = o
$test->TestComments[$type]
将包含相同的值,包括最后一条注释及其用户名和时间戳
public function getComment($test) {
$Id = $test->Id;
$localComment = new stdClass();
$queryComment = $this->getResultCommentQuery($Id);
$result = odbc_exec($this, $queryComment);
$no_results = odbc_num_rows($result);
for ($i = 1; $i <= $no_results; $i++) {
odbc_fetch_row($result, $i);
$type = trim(odbc_result($result, "result"));
$localComment->Comment = trim(odbc_result($result, "comment"));
$localComment->Username = trim(odbc_result($result, "username"));
$localComment->Timestamp = trim(odbc_result($result, "timestamp"));
$test->TestComments[$type] = $localComment;//there are no unique
//values here, every comment will have the same "timestamp", "comment", and "username", namley the last one.
echo($localComment->Comment);//If I do this I see that there are different values.
}
return $test; //But this will only contain a correct nr of array attributes with same content (last comment info), see bellow.
}
也就是说,我两次获得相同的内容,而不是两行不同的值。有人知道可能出了什么问题吗
提前感谢。您的问题是使用
$test->TestComments[$type] = $localComment;
这不是你想的那样。它实际上是将对象的引用复制到$test->TestComments[$type]
而不是对象本身的内容
因此,由于您只有一个实际的$localComment
对象,因此所有这些引用都指向该对象,该对象将包含最后放入该对象的内容
实际上,您要做的是克隆对象,这将创建对象的副本,而不仅仅是为原始对象指定引用
所以改变这条线
$test->TestComments[$type] = $localComment;
到
您现有的代码应该可以正常工作。我猜odbc_result($result,“result”)会为所有行返回相同的结果(或没有结果),因此$type总是相同的$test->TestComments[$type]在每次迭代中都会被覆盖,最后您只拥有最后一行。你能用var_dump($type)看看它在每次迭代中得到了什么值吗?最后一分钱掉了下来,我找出了到底是什么错了。我更改了答案以反映实际错误和正确的修复。我希望你不介意,如果它是错误的,我相信你可以删除正确的答案学分。
$test->TestComments[$type] = $localComment;
$test->TestComments[$type] = clone $localComment;