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.
In my opinion, you’re breaking encapsulation by trying to do this:
You should not be modifying
$a‘s state from within$b. You should only modify$b‘s state from within$b, and tell$ato modify its own state: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 likeunset($array[$index]), and there are a few other different methods, as well.