【发布时间】:2023-03-08 19:57:01
【问题描述】:
我是 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?
?>
好的,我更新我的问题,实际上,没有具体问题。我只想知道数组对象在插入新值之前和之后是否保持不变。 在 Python 中,我可以进行这样的测试:
a = [1]
print id(a)
a.append(2)
print id(a)
顺便说一句,这是 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.)
代码更新:
# -*- 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
所以问题是我可以通过 C++/Python/Java 中的代码来证明内存布局,我想确定我是否可以在 PHP 中做同样的事情。
【问题讨论】:
-
你需要解决什么问题?您的代码没有给出太多提示......当您将元素附加到 C++ 时,它会创建一个全新的数组,这听起来很奇怪:-?
-
我对C++/python/Java一无所知,但是在php中添加新元素时数组是一样的。
-
PHP 没有任何这样的机制。您必须描述您要解决的问题,以便我们建议在 PHP 中解决问题的适当方法。
-
@Epodax 是的,OP 似乎担心 数组 可能出于某种原因变成一个新实例。我认为在 PHP 中担心这是错误的事情。
-
@python 关于你所有的 Python 示例:如果你在 PHP 中做同样的事情,你的数组 将 不同。
$c = $a将创建一个新的数组副本/实例。无需证明,这是给定的。
标签: php