2014-04-15 39 views
0

我徘徊爲什麼這不會將數組值添加到對象。將值添加到對象內的屬性。

<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";的方式,但沒有得到補充,忍者。

這可能是什麼問題和解決方案?

回答

1

您可以使用array_push

array_push($names->children_names, "ninja"); 
1
$names = new people_names; 
$children = **$name**->children_names[] = "ninja"; 

您是不是應該訪問$ names,因爲它是您創建的對象?

編輯:忘了 - >

<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

如果您使用的是PHP < 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"); 
}