0

Not very good at putting this question into words....

I'm using an API to update some customer information

$customer =             new Customer();
$customer->first_name = $value;
$customer->update();

The above would update the first_name, however I'd like to variable where first name is like:

$attribute =                'first_name';    
$customer =                 new Customer();
$customer->$attribute =     $value;
$customer->update();`

Which would then reference the public vars in the Customer class.

I want to avoid writing a method(setter) for every attribute.

9
  • 3
    have you tried the above? Dit it work? If so, what is the question? Commented Dec 6, 2010 at 10:48
  • $customer->{$attribute} = $value; Commented Dec 6, 2010 at 10:51
  • 1
    Your problem is probably the typo $attrubute. Commented Dec 6, 2010 at 10:52
  • (reference) Variable variables Commented Dec 6, 2010 at 10:52
  • 1
    I'd say your problem isn't connected with the code you provided. Could you please provide a complete working example or show us var_dump($customer)? Commented Dec 6, 2010 at 10:56

2 Answers 2

2

Both $obj->$attr and $obj->{$attr} will work in the same way. The {} are redundant in this case. They make sense when you need to write something like $obj->{"123"}.

<?php
$obj = new stdClass();
$attr = 'my_attr';
$obj->$attr = 'test'; 
var_dump($obj);
?>

The problem with your code is that you have a typo. Or if the typo was only in the text of question, then you don't have any problem.

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

2 Comments

Cool these both work, in what cases would the braces be appropriate? arrays?
@Haroldo When there is ambiguity or when the syntax isn't allowed. Ex. $obj->{$arr[3]} instead of $obj->$arr[3] or $obj->{"123"} instead of $obj->123.
0

you can do it like

$attr = 'my_attr';
$obj->{$attr}; 

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.