Reputation: 213
I have an array of objects (A) which has an array of objects (B) inside it.
I'm trying to move B to a different object in array A.
I'm trying to use this:
public function killToken($a) {
array_push($a->tokens,$this); // Put this token in new array (works)
unset($this); // Remove token from this array (does not work)
}
I call this function via: $b->killToken($a);
I've tried several variations on this, but I just can't figure out how to get rid of the object from inside itself.
Any help would be appreciated.
Upvotes: 1
Views: 224
Reputation: 28889
In my opinion, you're breaking encapsulation by trying to do this:
array_push($a->tokens,$this);
You should not be modifying $a
's state from within $b
. You should only modify $b
's state from within $b
, and tell $a
to modify its own state:
$b->killToken($a); // only removes $a from $b->tokens
$a->addToken($b); // adds $b to $a->tokens
This is one of the basic principles of OO design.
Edit: That being said, unset($foo)
is not how you remove an element from an array. You can array_search() for the element, which will give you the index, and then you can unset the index like unset($array[$index])
, and there are a few other different methods, as well.
Upvotes: 2