While循环以更改php中的对象属性


While loop to change object property in php

我在foto类中的listByEvent函数中得到了while循环,以检索我的db-fotos:

    while ($fetch_query = mysql_fetch_assoc($get_foto)) {
        $this -> idFoto = $fetch_query['idFoto'];
        $this -> arquivo = $fetch_query['arquivo'];
        $this -> legenda = $fetch_query['legenda'];
        $this -> idEvento = $fetch_query['idEvento'];
        $this -> curtidas = $fetch_query['curtidas'];
        $this -> naocurtidas = $fetch_query['naocurtidas'];
        $fotos[] = $this;
    }
             return $fotos;

然后在我的视图(show.php)中,我调用这样的方法:

                $foto = new foto();
                $foto -> idEvento = $key -> idEvento;
                $fotos = $foto -> listByEvent();
                foreach ($fotos as $fotokey) {
                                    //here i proper format the layout
                                     }

但是while循环不能覆盖$this属性,它总是检索相同的foto。如果我更改fc以调用新的obj,如下图所示:

            while ($fetch_query = mysql_fetch_assoc($get_foto)) {
        $jack = new foto();
        $jack -> idFoto = $fetch_query['idFoto'];
        $jack -> arquivo = $fetch_query['arquivo'];
        $jack -> legenda = $fetch_query['legenda'];
        $jack -> idEvento = $fetch_query['idEvento'];
        $jack -> curtidas = $fetch_query['curtidas'];
        $jack -> naocurtidas = $fetch_query['naocurtidas'];
        $fotos[] = $jack;
    }
            return $fotos;

比它有效。有人能解释为什么我不能在while循环中覆盖这些方法吗?感谢您抽出时间

当您分配类对象时,您不进行复制,您只是为对象分配一个引用。因此,在您的第一个循环中,所有数组元素都引用同一个$this对象,您每次在循环中都会修改该对象。您需要使用new来创建新对象,以便阵列元素是不同的。

this指针是一个只能在类、结构或联合类型的非静态成员函数中访问的指针。它指向调用成员函数的对象静态成员函数没有此指针。

因此这个指针返回相同的值。

因此,您需要创建一个新对象来保存这些值。这就是它在第二个循环中工作的原因。