【问题标题】:PHP arrays work differently for objects vs values [duplicate]PHP数组对对象和值的工作方式不同[重复]
【发布时间】: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> 当它是一个值数组时会复制到该项目,但当它是一个对象数组时则不然。如何让它将对象复制到数组而不是复制对对象的引用?每次需要向数组添加对象时,是否需要创建一个新对象?

【问题讨论】:

  • 那是因为字符串数组和对象就是这样工作的。它们很难混合

标签: php arrays


【解决方案1】:

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

Demo on 3v4l.org

【讨论】:

    【解决方案2】:

    $x = new X(); 将对对象的引用存储到$x 中。随后的$y = $x; 复制的是引用,而不是对象,所以$x$y 都引用同一个对象。

    PHP 在引用方面具有相当复杂的语义。

    【讨论】:

      【解决方案3】:

      对象总是引用;您对 $word 的所有使用都指的是相同的对象和相同的数据结构。你需要做的:

      $class_words=[new word('this'),new word('that')];
      

      【讨论】:

        【解决方案4】:

        数组的两个元素都包含同一个对象。因此,每当您对该对象进行更改时,对该对象的所有引用都将显示该更改——它们都指的是 当前状态 中的相同对象

        如前所述,如果您想要不同的值,您需要实例化新对象,或者通过返回简单值(字符串、整数、布尔值等)而不是对象本身的 getter() 获取属性值.

        附带说明一下,您可以利用对象的引用特性来链接方法 ($Obj->method1()->method2()->method3()),方法是让方法返回对对象的引用,即 return $this;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-08-18
          • 2017-11-12
          • 1970-01-01
          • 2020-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-11
          相关资源
          最近更新 更多