Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php访问类属性数组时出错,不是数组_Php_Arrays_Oop - Fatal编程技术网

php访问类属性数组时出错,不是数组

php访问类属性数组时出错,不是数组,php,arrays,oop,Php,Arrays,Oop,试图获取数组中的值,但返回错误: 警告:为foreach()提供的参数无效 使用array\u key\u exists()时: 警告:array_key_exists()要求参数2为数组 为什么属性数组$credentials在这里不能识别为数组 class Config { private $credentials = array( 'host' => 'localhost', 'dbname' => 'testdb', 'u

试图获取数组中的值,但返回错误:

警告:为foreach()提供的参数无效

使用
array\u key\u exists()时

警告:array_key_exists()要求参数2为数组

为什么属性数组
$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作为局部变量。如果要引用实例变量,则必须使用符号$->variableName。在实例方法中,可以使用$this->credentials。但是,您处于一个静态函数中,该函数没有关联的对象。因此,不能引用实例变量

在您的调用函数中,您必须有一个对类Config(比如$myConfig)对象的引用,并调用一个名为“get”的方法,如


“get”需要声明为方法,而不是静态函数。然后,方法“get”可以以$this->credentials的形式访问实例变量“credentials”。

即使在编辑问题之后,静态函数中的$credentials是一个局部变量,而方法中的$this->credentials将是访问所需变量的方式。确定,谢谢。我会搞砸的。虽然将从静态方法访问的不是
self
,但不是您声明变量的方式。请注意使用self关键字,您必须更改变量的声明。就是这样!非常感谢。
private $credentials 
$myConfig->get($credential);