[英]php accessing class property array, error not an array
Trying to get the values in an array but returning an error:尝试获取数组中的值但返回错误:
Warning: Invalid argument supplied for foreach()
警告:为 foreach() 提供的参数无效
and when using array_key_exists()
:当使用
array_key_exists()
:
Warning: array_key_exists() expects parameter 2 to be array
警告:array_key_exists() 期望参数 2 为数组
Why is the property array $credentials
not recognized as an array here?为什么这里的属性数组
$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
declares an instance variable.声明一个实例变量。 You reference $credentials as a local variable.
您将 $credentials 引用为局部变量。 If you would want to reference the instance variable, you would have to use the notation $<object>->variableName.
如果要引用实例变量,则必须使用符号 $<object>->variableName。 In an instance-method, you could use $this->credentials.
在实例方法中,您可以使用 $this->credentials。 But, you are in a static function, which does not have an associated object.
但是,您处于一个没有关联对象的静态函数中。 Therefore, you cannot reference an instance variable.
因此,您不能引用实例变量。
In your calling function you would have to have a reference to an object of class Config (let's say $myConfig) and call a method of the name "get", like在您的调用函数中,您必须引用类 Config(假设为 $myConfig)的对象并调用名为“get”的方法,例如
$myConfig->get($credential);
"get" would need to be declared a method and not a static function. “get”需要声明为方法而不是静态函数。 Then the method "get" could access the instance variable "credentials" as $this->credentials.
然后方法“get”可以访问实例变量“credentials”作为$this->credentials。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.