2013-03-12 73 views
2

我想取消設置類的成員變量數組的第一個值,但我不能給:如何在PHP類成員變量未設置數組值動態

<?php 

class A 
{ 
    public function fun() 
    {  
     $this->arr[0] = "hello"; 
    } 

    public $arr; 
} 


$a = new A(); 
$a->fun(); 
$var ="arr"; 

unset($a->$var[0]); //does not unset "hello" value 

print_r($a); 

我找不到任何後解決在Google中搜索。我如何動態刪除第一個值?

+0

'$ a'是一個對象,使用'var_dump($ a)'和'$ var [0]'會給你'a'。你想要刪除什麼? – vedarthk 2013-03-12 10:25:05

+0

對於數值索引數組的進一步問題和未設置,請看下面的答案,祝你有愉快的一天。 – Ihsan 2013-03-12 10:57:52

回答

2

嘗試以下操作:

unset($a->{$var}[0]); 

與您的代碼的問題是,PHP嘗試訪問成員變量$var[0](這是null),而不是$var

0

您可以array_shift嘗試:

array_shift($a->{$var}); 

此功能與陣列的一開始就使用參考值,並移除(返回)值。

0
<?php 

    class A 
{ 
    public function fun() 
    {  
     $this->arr[0] = "hello"; 
    } 

    public $arr; 
} 


$a = new A(); 
$a->fun(); 

// no need to take $var here 
// you can directly access $arr property wihth object of class 

/*$var ="arr";*/ 

// check the difference here 
unset($a->arr[0]); //unset "hello" value 

print_r($a); 

?> 

試試這個

0

因爲$改編爲A類的成員,並宣佈公開,您可以直接使用

$a = new A(); 
$a->fun(); 
unset $a->arr[0]; 

但你會驚奇地發現,對於數字索引的數組,未設置可能會帶來問題。

假設你的數組是這樣的;

$arr = ["zero","one","two","three","four"]; 
unset($arr[2]);  // now you removed "two" 
echo $arr[3];   // echoes three 

現在array爲[「zero」,「one」,undefined,「three」,「four」];

$ ARR [2]不存在,它是未定義的,並使用下面的方法是較好的其餘部分不重新索引...

爲數字索引數組:

$arr = ["zero","one","two","three","four"]; 
array_splice($arr,2,1); // now you removed "two" and reindexed the array 
echo $arr[3];   // echoes four... 

現在陣列是[「零」,「一」,「三」,「四」];