2017-01-22 89 views
0

我正在學習(好,試圖)OOP,我有一個簡單的,可能非常愚蠢的問題。 我不得不從一個非常「深」的數組中檢索一些數據。如果我是使用一種過程化的做法,我想聲明一個變量就是這樣,只是可讀性的原因:PHP - 雖然/在課堂上的foreach:卡住,不知道該怎麼辦

foreach ($my_array as $single) { 

     $readable = $single['level_1']['level_2']['level_3']['something']; 

    } 

儘管這裏面的foreach,我可以用$readable,因爲我喜歡。 現在我試圖建立一個類,我需要處理相同的數組。我會很想做這樣的事情,以使事情更清楚:

class MyClass { 

protected $my_array = null; 

protected function myCustomIncrement() { 

    return $readable++; 

} 

public function myCustomOutput() { 

    foreach ($this->my_array as $single) { 

     $readable = $single['level_1']['level_2']['level_3']['something']; 

     return $this->myCustomIncrement(); 

    } 


} 

} 

$test = new MyClass; 
echo $test>myCustomOutput(); 

不過,雖然裏面myCustomIncrement()$readable$this->$readable結果不確定。我可能試圖做一些非常愚蠢的事情,這就是爲什麼我想尋求幫助:我如何使用foreach或者保持清晰/可讀/可維護的代碼?或者,也許我應該使用不同的方法?

在此先感謝!

回答

1

您需要將$readable的值傳遞給myCustomIncrement()方法,並使其增加。所以,你的myCustomIncrement()myCustomOutput()方法將是這樣的:

protected function myCustomIncrement($readable) { 
    return ++$readable; 
} 

public function myCustomOutput() { 
    foreach($this->my_array as $single) { 
     $readable = $single['level_1']['level_2']['level_3']['something']; 
     return $this->myCustomIncrement($readable); 
    } 
} 

把增加操作的預增量樣return ++$readable;,沒有後遞增,因此,該方法可以返回更新後的值。

+0

只是一個旁註,照顧'foreach'循環內的'return'語句。在當前場景中,一旦命中'return'語句,控件就會返回到調用函數語句。所以基本上,你的'foreach'循環只會執行一次**。 –

+0

謝謝!我認爲把$可讀爲參數,但我只爲myCustomIncrement()做了這個。並且非常感謝您的其他提示! – Cerere