2

我有一个存储一些员工对象的数组,即。

var $this->employeeArray = array();
$this->employeeArray[] = $empObjectA;
$this->employeeArray[] = $empObjectB;
...

哪个 Employee 对象具有 id、firstName、lastName 等。我还有一个函数可以搜索具有特定 ID 的员工对象。IE:

public function searchArrayByID($id) {
$targetObject = null;

        foreach($this->employeeArray as $e) {
            if ($id == $e->id) {
                $targetObject = $e;
                break;
            }
        }//foreach

return $targetObject;

}

但是当我这样做时:

$targetEmployee = $this->searchArrayByID(1);
$targetEmployee->firstName = "someOtherName";

并做一个

print_r($this->employeeArray);

数组中的那个对象没有被改变。

4

2 回答 2

2

试试这个,加上&前面,它将通过参考。我还简化了您的搜索功能。

因为我不知道为什么它不适合你,因为它在 2 个不同的服务器上为我工作而没有任何&我可以建议“最安全”的方法 => 尽可能强制引用

$this->employeeArray[] = &$empObjectA;  // here

public function &searchArrayByID($id) {   // here
    foreach($this->employeeArray as &$e) {   // and here
        if ($id == $e->id) return $e;
    }
    return null;
}

$targetEmployee = $this->searchArrayByID(1);

现在,如果这不起作用,我怀疑您的代码中存在另一个错误,因为这里强制每个引用

有趣的是。我在这里尝试过:http: //phpfiddle.org/main/code/2cv-pt2 并且使用该php版本,它没有区别(应该是这样)。您使用的是哪个 php 版本?因为 PHP 在处理引用方面做得更好(减少了不需要的/不必要的副本)

于 2013-08-07T14:52:35.633 回答
0

那是因为 PHP 将对象复制到 $targetEmployee,它没有链接。

于 2013-08-07T14:49:57.150 回答