Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP extract into class variables

Tags:

php

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?

like image 884
Lee Loftiss Avatar asked Dec 08 '22 12:12

Lee Loftiss


2 Answers

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.

like image 160
Styxxy Avatar answered Dec 15 '22 00:12

Styxxy


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;
    }
}
like image 22
zamnuts Avatar answered Dec 14 '22 23:12

zamnuts