3

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 Answers 2

3

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.

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

1 Comment

Perfect. I had never worked with keys inside of a foreach. Thanks for excusing my ignorance. :)
1

Why don't you use a foreach loop?

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

Comments

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.