How is parenting functions in PHP done properly according to the following example?
Can I make sure that my array isn’t overwritten and the previous values inside array lost, on each addArray call?
function arraybase() {
$this->array = new ArrayObject();
return $this;
}
function addArray($value) {
parent::$this->arraybase();
$this->array->append($value);
return $this;
}
$this->addArray('1')->addArray('2')->addArray('3');
// outputs:
Array
(
[0] => 3
)
Well, first off, you don’t need to
parent::$this->arraybase(). Just do$this->arraybase(). In fact, I’m not even sure your way is even valid syntax. But I digress.As for your specific problem, you can either:
Add a constructor (and remove the
->arraybase()call fromaddArray()):Add an if check around the call to
->arraybase():Personally, I’d do #1. It’s going to be more reliable, faster, and more in keeping with OOP paradigms.
EDIT: Adding Constructor Info
So, if your base class has this constructor:
You would do this in your extending class:
NOTE: Don’t call
parent::__construct()unless one of the parents has a __construct method…