1

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?

1 Answer 1

1

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.

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

3 Comments

Thank you. Do you know of any documentation that may state the above?
@mavrosxristoforos, it's a basic feature of PHP since 5.0, you can start from here: php.net/manual/en/oop5.intro.php
Thank you. I have seen the oop5 documentation, indeed, and this is working as expected, so I'll just rest assured for now.

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.