简体   繁体   English

为什么我的变量不指向同一数组?

[英]Why aren't my variables pointing to the same array?

I have two classes. 我有两节课。 One that has the array ( ArrayStorage ) and the other ( ArrayConsumer ) has just a variable that will act as a simple reference to an array. 一个拥有数组( ArrayStorage ),另一个拥有ArrayConsumer的变量只是一个对数组的简单引用。

I add a new element to the array using $my_array . 我使用$my_array将新元素添加到数组中。 Then I check to see if the new element is visible in the $obtained_array . 然后,我检查新元素在$obtained_array是否可见。 But the test fails because it cannot find the new element. 但是测试失败,因为它找不到新元素。 They act like they were different arrays. 它们的行为就像是不同的阵列。 Shouldn't they point to the same array? 他们不应该指向同一个数组吗?

public function testArrayMadness() {
        $arrayStorage = new ArrayStorage();
        $my_array = $arrayStorage->getArray();

        $arrayConsumer = new ArrayConsumer($my_array);
        $obtained_array = $arrayConsumer->getArray();

        $my_array[3]='c';
        $this->assertContains('c', $obtained_array);
    }
}
class ArrayStorage {
    private $my_array=[1=>'a',2=>'b'];
    function getArray() { return $this->my_array; }
}
class ArrayConsumer {
    private $obtained_array;
    function __construct($array) { $this->obtained_array=$array; }
    function getArray() { return $this->obtained_array; }
}

Update: I did the same on test in Java, it gives me an indexOutOfBoundsException. 更新:我在Java测试中做了同样的事情,它给了我indexOutOfBoundsException。 Does that mean both php and java works the same way in this aspect or is there something wrong with my code? 这是否意味着php和java在这方面的工作方式相同,还是我的代码有问题?

@Test
    public void testArrayMadness() {
        ArrayStorage arrayStorage = new ArrayStorage();
        List<String> my_list = arrayStorage.getList();

        ArrayConsumer arrayConsumer = new ArrayConsumer(my_list);
        List<String> obtained_array = arrayConsumer.getList();

        my_list.add("c");
        assertEquals("c", obtained_array.get(3));
    }
}

class ArrayStorage {
    private List<String> my_list;
    public ArrayStorage() {
        my_list = new ArrayList<>();
        my_list.add("a");
        my_list.add("b");
    }
    public List<String> getList() { return my_list; }
}
class ArrayConsumer {
    private List<String> obtained_list;
    public ArrayConsumer(List<String> list) {
        this.obtained_list = list;
    }
    public List<String> getList() { return this.obtained_list; }
}

PHP arrays are not objects, they are assigned by value: PHP数组不是对象,而是通过值分配的:

$a = [1,2,3];
$b = $a;
$b[2] = 99;

print_r($b); // 1,2,99
print_r($a); // 1,2,3

A workaround is to use reference signs & (a bad idea generally) or ArrayObject s: 一种解决方法是使用参考符号& (通常是个坏主意)或ArrayObject

$a = new ArrayObject([1,2,3]);
$b = $a;
$b[2] = 99;

print_r($b); // 1,2,99
print_r($a); // 1,2,99

使用&运算符返回引用数组,例如return &$this->my_array;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM