数组成员不会保存

时间:2016-03-10 19:49:44

标签: php

我学习php并遇到下一个代码的麻烦:

    $people = new people();
    $people->getByNumber($value[0]);    
    $peoples = array();
    $count_people = 5;
    for($i=1; $i<=$count_people; $i++)
    {
        $people->getByNumber($i);
        $peoples[$i] = $people;
        print_r($peoples[$i]);
    }
    print_r($peoples);

所以在循环“for”$peoples之后不显示任何信息并且print_r告诉,该数组由空值组成(但存在键)。循环工作时,print_r内部显示正确的对键 - >值。如何修复它以便在循环后使用$peoples

UPD: 在for {循环中print_r($peoples[$i]);我可以看到:

people Object
 (
    [id] =&gt; 1
    [age] =&gt; 19
    [short_name] =&gt; Jhon
    [full_name] =&gt; Jhon Persh
    [image] =&gt; 
 )

但是for-loop $peoples仅包含:

Array
(
    [1] =&gt; people Object
        (
            [id] =&gt; 
        [age] =&gt; 
        [short_name] =&gt; 
        [full_name] =&gt; 
        [image] =&gt; 
        )

    [2] =&gt; people Object
        (
            [id] =&gt; 
        [age] =&gt; 
        [short_name] =&gt; 
        [full_name] =&gt; 
        [image] =&gt;  
        )

    [3] =&gt; people Object
        (
            [id] =&gt; 
        [age] =&gt; 
        [short_name] =&gt; 
        [full_name] =&gt; 
        [image] =&gt; 
        )

    [4] =&gt; people Object
        (
            [id] =&gt;
        [age] =&gt; 
        [short_name] =&gt; 
        [full_name] =&gt; 
        [image] =&gt;  
        )

    [5] =&gt; people Object
        (
          [id] =&gt; 
          [age] =&gt; 
          [short_name] =&gt; 
          [full_name] =&gt; 
          [image] =&gt; 
        )

)

UPD2:

public function getByNumber($id)
    {
        $classProperty = get_object_vars($this);
        foreach ($classProperty as $key=>$value)
            $member[] = $key;

        $data = //random data generation;
        foreach ($member as $key =>$field)
        {
            $this->$field = $data[$field];
        }
    }

2 个答案:

答案 0 :(得分:0)

在for循环中,您将$peoples[$i]设置为$people,但没有名为$people的变量。您拨打$people->getByNumber($i)但不要将其保存在任何地方。

你的for循环应该是这样的:

$p = $people->getByNumber($id);
$peoples[$i] = $p;

答案 1 :(得分:0)

我在类$ people1 = new People()的construcnt新对象中找到了答案,然后在循环调用方法getByNumber($ id)后使用$ peoples [] = $ people1; 顺便说一句,不知道为什么复制构造函数不会自称。