我学习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] => 1
[age] => 19
[short_name] => Jhon
[full_name] => Jhon Persh
[image] =>
)
但是for-loop $peoples
仅包含:
Array
(
[1] => people Object
(
[id] =>
[age] =>
[short_name] =>
[full_name] =>
[image] =>
)
[2] => people Object
(
[id] =>
[age] =>
[short_name] =>
[full_name] =>
[image] =>
)
[3] => people Object
(
[id] =>
[age] =>
[short_name] =>
[full_name] =>
[image] =>
)
[4] => people Object
(
[id] =>
[age] =>
[short_name] =>
[full_name] =>
[image] =>
)
[5] => people Object
(
[id] =>
[age] =>
[short_name] =>
[full_name] =>
[image] =>
)
)
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];
}
}
答案 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; 顺便说一句,不知道为什么复制构造函数不会自称。