Thursday, July 31, 2008

Adding class instances to Array()

I was coding a script halfway, when i ran into this case that i had never encounter before: adding class instances into arrays. I asked myself, was that possible? Well, the answer will reveal below.

<?php

class pClass{

public $_array = array();

public function display(){
print_r($this->_array);
}

}

$p = new pClass();
$second = new pClass();
$p->_array[] = $second;
// IT IS POSSIBLE! xD
$p->display(); // outputs: Array ( [0] => pClass Object ( [_array] => Array ( ) ) )
// how cool.

?>


Fortunately, i tested and it works. I added a class instance to the array of another class. On top of that, the both can be instances of the same class. Well, this allows parent-children relationships of classes.

In addition, this will allow recursive addition of class, since it is a class in a class. Well, why not?

Adding class instances to array would mean that multiple instances can also be added to one class, via this method too!

No comments: