php - PHP 数组对对象和值的工作方式不同
问题描述
这是我的代码:
$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>
会复制到该项目,但当它是一个对象数组时却不是这样。如何让它将对象复制到数组而不是复制对对象的引用?每次需要向数组添加对象时,是否需要创建一个新对象?
解决方案
如果要将对象的值复制到数组中,则需要为该值编写一个“getter”,例如
class word{
private $text;
public function __construct($word){
$this->text=$word;
}
public function setWord($word){
$this->text=$word;
}
public function getWord() {
return $this->text;
}
}
$class_words = array();
$word = new word("this");
$class_words[] = $word->getWord();
$word->setWord("that");
$class_words[] = $word->getWord();
print_r($class_words);
输出:
Array
(
[0] => this
[1] => that
)
推荐阅读
- xamarin.forms - Xamarin Forms Android 项目 TargetFrameworkVersion 更新到 Xamarin Forms 5 后出现错误
- containers - Service Fabric - 在 IIS 上的容器中运行的 .net 4.7.2 应用程序可以访问结构配置设置吗?
- vba - 尝试使用 VBA 更新注册表项。错误:“注册表项中的根无效...”
- sql - 当有两行满足查询时,PostgreSQL 查询仅返回一行
- python - mysql上的表关系以计算新字段
- c++ - C ++为什么这种结构甚至有效?
- sql - 在 SQL Server 2016 上使用 STUFF 和 XML PATH 时如何返回空白或空记录?
- azure-devops - Azure DevOps 管道资源触发器不起作用
- c# - C# Main Form BackColor 在图像前面移动
- javascript - 我只得到第二个 .innerHTML 结果,第一个没有运行