我在徘徊为什么这不会向对象添加数组值。
<pre>
<?php
class people_names{
public $children_names = ["hanna", "danny", "toddy"];
public $teen_names = ["shewit", "rahel", "elizabeth"];
public $old_people_names = ["douglas", "bob", "michael"];
}
$names = new people_names;
$children = $name->children_names[] = "ninja";
var_dump($name->children_names);
当然,必须有一种方法可以为$children_name
我尝试了$children = $name->children_names[] = "ninja";
和$children = $name->children_names = "ninja";
,但该忍者没有被添加。
这可能是什么问题和解决方案?
答案 0 :(得分:1)
$names = new people_names;
$children = **$name**->children_names[] = "ninja";
你不应该访问$ name,因为它是你创建的对象吗?
编辑:忘记 - &gt;
<pre>
<?php
class people_names{
public $children_names = ["hanna", "danny", "toddy"];
public $teen_names = ["shewit", "rahel", "elizabeth"];
public $old_people_names = ["douglas", "bob", "michael"];
}
$names = new people_names;
$children = $names->children_names[] = "ninja";
var_dump($names->children_names);
答案 1 :(得分:1)
您可以使用array_push
:
array_push($names->children_names, "ninja");
答案 2 :(得分:1)
如果您使用的是PHP&lt; 5.4我建议你这样做:
class people_names{
public $children_names = array("hanna", "danny", "toddy");
public $teen_names = array("shewit", "rahel", "elizabeth");
public $old_people_names = array("douglas", "bob", "michael");
}