tags:

views:

52

answers:

3

Hi everyone,

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
)

Thanks a lot!

+2  A: 

In function addArray you keep recreating the array with the line:

parent::$this->arraybase();

Remove this line and call arraybase when you want to create it.

webbiedave
+1  A: 

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:

  1. Add a constructor (and remove the ->arraybase() call from addArray()):

    public function __construct() {
        $this->array = new ArrayObject();
    }
    
  2. Add an if check around the call to ->arraybase():

    public function addArray($value) {
        if (!isset($this->array) || !is_object($this->array)) {
            $this->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:

public function __construct($some, $vars) {
    ......
}

You would do this in your extending class:

public function __construct($some, $vars) {
    parent::__construct($some, $vars);
    $this->array = new ArrayObject();
}

NOTE: Don't call parent::__construct() unless one of the parents has a __construct method...

ircmaxell
I cant make __construct without affecting all the other functions (methods?) in the same class, right?
Industrial
Sure you can. If you need to call the parents constructor, just call `parent::__construct()` from your constructor. You'll need to make sure you supply the correct arguments, but that's the whole point of OOP. To be able to "extend" functionality. Not just use it...
ircmaxell
Hi, i didn't understand you there at all. Do you mind updating your post with an example? Thanks a lot!
Industrial
Thanks a lot for your help!
Industrial
A: 

Why do you want to set a wrapper around ArrayObject? If it's for adding the possibility of chaining method calls, then you'd better extend ArrayObject:

<?php
class MyArrayObject extends ArrayObject {

    public function append($value)
    {
        parent::append($value);
        return $this;
    }
}

$ao = new MyArrayObject();
$ao->append('a')->append('b')->append('c');
var_dump($ao->getArrayCopy());
/*
array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}
*/
nuqqsa