-1

Trying to get the values in an array but returning an error:

Warning: Invalid argument supplied for foreach()

and when using array_key_exists():

Warning: array_key_exists() expects parameter 2 to be array

Why is the property array $credentials not recognized as an array here?

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');
Hezerac
  • 334
  • 1
  • 5
  • 20

1 Answers1

1
private $credentials 

declares an instance variable. You reference $credentials as a local variable. If you would want to reference the instance variable, you would have to use the notation $<object>->variableName. In an instance-method, you could use $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

$myConfig->get($credential);

"get" would need to be declared a method and not a static function. Then the method "get" could access the instance variable "credentials" as $this->credentials.

Florian Heer
  • 694
  • 5
  • 17
  • Even after editing the question, $credentials in a static function is a local variable, whereas $this->credentials in a method would be the way to access the variable you want. – Florian Heer Oct 01 '16 at 01:17
  • OK thanks. I'll mess with that. Although isnt it `self` that will access from a static method? – Hezerac Oct 01 '16 at 01:26
  • not the way you declared the variable. Please look at http://stackoverflow.com/questions/151969/when-to-use-self-over-this For using the self keyword, you have to change the declaration of the variable. – Florian Heer Oct 01 '16 at 01:31
  • Thats it! Thank you. – Hezerac Oct 01 '16 at 13:48