0

I would like to pre-define my object variables into an array. After that, I need to access one element at a time from that array and assign a value to it. Like so:

$obj = new StdClass();
$arr = ["$obj->item1"];
$arr[0] = "apple";
print_r($obj); // expecting to see $obj->item1 = apple

I know I'm doing something wrong above, but could not figure out what.

2
  • you’re overwriting $arr[0], instead of assigning the property of $obj. What’s probably messing you up is that objects pass by reference; but arrays by value. Commented Jul 19, 2020 at 3:02
  • 1
    If you assign just the object to $arr[0], then you might possibly be able to set $obj->item1 somewhere else in the code, and then reference $arr[0]->item1. Commented Jul 19, 2020 at 3:10

1 Answer 1

1

Solved. Thanks to the hint from Tim Burton

$arr = [&$obj->item1];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.