-1
試圖得到在數組中的值,但返回一個錯誤:PHP訪問類屬性數組,錯誤不是數組
Warning: Invalid argument supplied for foreach()
,並使用array_key_exists()
時:
Warning: array_key_exists() expects parameter 2 to be array
爲什麼屬性數組$credentials
在這裏不被識別爲數組?
class Config {
private $credentials = array(
'host' => 'localhost',
'dbname' => 'testdb',
'user' => 'username',
'pass' => 'password'
);
public static function get($credential) {
if(array_key_exists($credential, $credentials)) {
foreach($credentials as $key => $value) {
if($key === $credential) {
return $credentials[$key];
}
}
return false;
} else {
echo 'Credential does not exist.';
}
}
}
$test = new Config();
echo $test->get('host');
即使在編輯問題之後,靜態函數中的$ credentials也是局部變量,而方法中的$ this-> credentials將是訪問所需變量的方式。 –
好的謝謝。我會搞砸的。雖然不是它會從靜態方法訪問的'self'? – Hezerac
不是你聲明變量的方式。請看http://stackoverflow.com/questions/151969/when-to-use-self-over-this 對於使用self關鍵字,您必須更改變量的聲明。 –