4

I am using PHP 5.3 and the extract() function.

Here is a simple example of a class I am building:

private api_username;
private api_password;
private api_signature;
private version = '63.0';

public function __construct($credentials) {
    extract($credentials);

    $this->api_username = $api_username;
}

The issue is that after the extract, I have to go one by one through the variables and assign them to the class variables.

Is there a way to extract directly to the class variables so I don't have to do the item by item assignment?

3 Answers 3

13

If the keys of the$credentials array match exactly to the names of the private variables, you can use variable variables to accomplish this (with the key as the variable).

public function __construct($credentials) {
    foreach($credentials as $key => $value) {
        $this->$key = $value;
    }
}

Though, make sure the array you pass in, has the correct keys.

Sign up to request clarification or add additional context in comments.

Comments

2

This probably isn't safe to do, and the method you're using goes against most accepted models, but:

foreach ( $credentials as $key => $value ) {
    if ( property_exists($this,$key) ) {
        $this->$key = $value;
    }
}

1 Comment

'the method you're using goes against most accepted models' Perhaps. But I have found that PHP is very good about stretching the definition of 'accepted models'.
0

you can try this :

extract($credentials, EXTR_REFS);
foreach ($credentials as $key => $value) {
      $this->$key = $$key;
}

2 Comments

Why go through the trouble of extracting and using double variable variables to get the value, while you have the value in a single variable of your loop?
indeed, $this->$key = $value;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.