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?
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With