首页 > 解决方案 > 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>会复制到该项目,但当它是一个对象数组时却不是这样。如何让它将对象复制到数组而不是复制对对象的引用?每次需要向数组添加对象时,是否需要创建一个新对象?

标签: phparrays

解决方案


如果要将对象的值复制到数组中,则需要为该值编写一个“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
)

3v4l.org 上的演示


推荐阅读