尝试获取数组中的值,但返回错误:
警告:为foreach()提供了无效参数
,当使用array_key_exists()
时:
警告:array_key_exists()期望参数2为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');
private $credentials
声明一个实例变量。您引用$credentials作为一个局部变量。如果要引用实例变量,则必须使用$
在你的调用函数中,你必须有一个对Config类对象的引用(比如$myConfig),并调用一个名为"get"的方法,比如
$myConfig->get($credential);
"get"需要声明为方法而不是静态函数。然后,方法"get"可以访问实例变量"credentials"作为$this->credentials。