我是来自C++/Python/Java的PHP的新用户.在PHP中,有一个内置的数组类型,如何在插入新对象或旧对象的副本后证明数组是相同的数组?在C++/Python/Java中,我可以使用对象地址,id()或hashcode来测试对象是否相同,如何在PHP中进行相同的测试?
<?php
$a['0'] = "a";
$a['1'] = 'b'; //here, $a is a new copied one or just a reference to the old?
?>
Run Code Online (Sandbox Code Playgroud)
好的,我更新了我的问题,实际上,没有具体的问题.我只是想知道在插入新值之前和之后数组对象是否保持相同.在Python中,我可以像这样进行测试:
a = [1]
print id(a)
a.append(2)
print id(a)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这是Python中的id()函数手册.
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
Run Code Online (Sandbox Code Playgroud)
代码更新:
# -*- coding: utf-8 -*-
a = [1, 2, 3]
b = [1, 2, 3]
print id(a)
print id(b) //the id(b) is not same as id(a), so a and b has same content, but they both own their own values in the memory
c = a // c is a reference to a
c.append(4)
print c
print a //after appending a new value(which means insert a new value to array), a has same value as c
Run Code Online (Sandbox Code Playgroud)
所以问题是我可以用C++/Python/Java中的代码来证明内存布局,我想确保我是否可以在PHP中做同样的事情.
默认情况下,在PHP中,只有对象通过引用分配.其他所有内容(包括数组)都按值分配.使两个指向同一数组的变量的唯一方法是使用&运算符显式设置引用.该引用的解释章给出了关于这个问题的一个很好的概述.
对于对象,您可以轻松地发现引用,即使只是简单var_dump():
$a = new DateTime;
$b = $a;
$c = clone $a;
var_dump($a, $b, $c);
Run Code Online (Sandbox Code Playgroud)
object(DateTime)#1 (3) {
["date"]=>
string(26) "2016-03-29 10:18:28.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Madrid"
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2016-03-29 10:18:28.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Madrid"
}
object(DateTime)#2 (3) {
["date"]=>
string(26) "2016-03-29 10:18:28.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Madrid"
}
Run Code Online (Sandbox Code Playgroud)
请注意#1由$a和共享的标识符$b.
其他类型根本不是微不足道的.在前面章节的Spotting References部分中,有一个用户评论,其中包含一些您可能想要检查的复杂代码,尽管它已经很老了.