【发布时间】:2019-08-09 08:35:18
【问题描述】:
这是我的代码:
$words = array();
$word = "this";
$words[] = $word;
$word = "that";
$words[] = $word;
print_r($words);
class word{
private $text;
public function __construct($word){
$this->text=$word;
}
public function setWord($word){
$this->text=$word;
}
}
$class_words = array();
$word = new word("this");
$class_words[] = $word;
$word->setWord("that");
$class_words[] = $word;
print_r($class_words);
exit;
这是输出:
Array
(
[0] => this
[1] => that
)
Array
(
[0] => word Object
(
[text:word:private] => that
)
[1] => word Object
(
[text:word:private] => that
)
)
我希望第二个输出与第一个输出匹配,因为数组应该存储“this”和“that”。似乎array_name[] = <item> 当它是一个值数组时会复制到该项目,但当它是一个对象数组时则不然。如何让它将对象复制到数组而不是复制对对象的引用?每次需要向数组添加对象时,是否需要创建一个新对象?
【问题讨论】:
-
那是因为字符串数组和对象就是这样工作的。它们很难混合