2015-10-13 63 views
3

我想訪問一個私有成員變量,用作數組中的鍵。如何使用私有php類成員變量作爲數組中的鍵?

我的類看起來與此類似:

<?php 
class MyClassName { 
    private $value; 
    private function MyFunction($array){ 
    $some_html = "<b> $array[$this->value] <b>"; // error occurring on this line 
    return some_html; 
    } 
} 
?> 

,我得到的錯誤是

PHP Parse error: syntax error, unexpected '-', expecting ']

如果我在陣列中使用它有之前存儲的私有成員變量沒有語法錯誤。這被解釋罰款:

<?php 
class MyClassName { 
    private $value; 
    private function MyFunction($array){ 
    $cache_key = $this->value; 
    $some_html = "<b> $array[$cache_key] <b>"; 
    return $some_html; 
    } 
} 
?> 

有什麼我失蹤?我想提高我對這裏發生的事情的理解。謝謝。

+0

又是什麼'MyFunction'回報,實際上,當你運行它(在第二種情況)? –

+0

你的第一個例子沒有什麼問題,在第二個例子中,你將'$ value'複製到'$ cache_key',但是沒有使用它。我的猜測是,你的真實代碼中有一處語法錯誤。 – doublesharp

+0

這裏工作:https://3v4l.org/MgG62 – AbraCadaver

回答

1

試試這個:

$some_html = "<b> ".$array[$this->value]." </b>"; 
+0

謝謝@DNT,解決了我的問題! – user3263538

相關問題