Question

I am unsure about my approach on changing property values of an object by its original pointer, after pushing it into an array.
In my parent class, there is an array of objects, and the function that pushes items into it returns the original instance.

class Parent {
  public $items;
  function __construct() { $items = array(); }

  function addItem() {
    $item = new stdClass();
    $item->foo = 'foo';
    $items[] = $item;  
    return $item;
  }
}

Inside the Child class, I get the original instance and I can easily change its foo property value:

class Child extends Parent {
  function newItem() {
    $item_instance = $this->addItem();
    $item_instance->foo = 'bar';
  }
}

When I instantiate the Child class, it behaves as expected, changing the array item property value of the parent class.

$my_child = new Child();
$my_child->newItem();
print $my_child->items[0]->foo; // prints 'bar'

My question is: Should I avoid using the original object pointer after the object is pushed into the array, or is this approach correct?

Was it helpful?

Solution

There is no reason to avoid using an object pointer after it is pushed into an array. What you push into an array is effectively the pointer, not the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top