3
votes

Trying to use a class that expects something like:

$client->firstname = 'bob';

$client->lastname = 'jones';

So I want to pass this data to the script in an array... where the keys and values are set elsewhere. I want to step through the array passing the key and value to the class. Trying to use this:

while($Val = current($CreateClientData)){

    $client->key($CreateClientData) = $Val;
    next($CreateClientData);
}

getting this:

Fatal error: Can't use method return value in write context in blahblahpath on line 40.

Line 40 being: $client->key($CreateClientData) = $Val;

How can I do this?

2

2 Answers

3
votes

If $client is already an instance of some class, and $CreateClientData is an array, then you probably wan to do something like this:

foreach($CreateClientData as $k => $v) {
    $client->{$k} = $v;
}

This assumes of course that every key in the array is a valid member of the $client instance. If not, then you will have to do some additional checking before assigning the value, or you will have to wrap the assignment in a try / catch.

EDIT
The answer as to why your code doesn't work is because PHP doesn't allow for assignment of class properties to certain functions that return values. In your case, key($CreateClientData) returns a key. So you could alter your code and just add

$key = key($CreateClientData);
$client->$key = $Val;

But, the foreach loop is a lot cleaner anyway.

1
votes

Why don't you use a foreach loop?

foreach($CreateClientData as $key => $val) {
    $client->$key = $val;
}