fanus.link Posted February 25, 2011 Share Posted February 25, 2011 In theory what I want is to have a object with an array of objects that consists of the same class but I do not know how to do it. I don't even know if it is possible. To better explain it I have thought of an example; I have an object called Cube. Inside the Cube can be multiple Cubes and inside those Cubes can also be multiple Cubes. The levels must be infinite. How will I do this in PHP and how will I initiate every Cube inside each other? I am new to PHP OOP but not OOP in general. I do understand the basic concept of OOP. Here is how my codes looks at the moment. The reason I might be struggling is because I'm use to declare arrays and that isn't done in PHP. class.bucket.inc.php <?php class Cube { private $_name; public $_cubes; public function __construct($name) { $this->_name = $name; } public function setName($name) { $this->_name = $name; } public function getName() { return $this->_name; } public function __toString() { return $this->_name; } } ?> index.php <?php $cube_one = new Cube('one'); $cube_one->_cubes = array(); $cube_two = new Cube('two'); $cube_two->_cubes = array(); $cube_one->_cubes[0] = new Cube('one_one'); $cube_one->_cubes[1] = new Cube('one_two'); $cube_one->_cubes[2] = new Cube('one_three'); $cube_two->_cubes[0] = new Cube('two_one'); $cube_two->_cubes[1] = new Cube('two_two'); ?> Am I doing it right? Eventually, the result I want must be something like this. <cube id="one"> <cube id="one_one"> </cube> <cube id="one_two"> </cube> <cube id="one_three"> </cube> </cube> <cube id="two"> <cube id="two_one"> </cube> <cube id="two_two"> </cube> </cube> Thanks, Fanus Quote Link to comment https://forums.phpfreaks.com/topic/228774-oop-an-object-with-an-array-containing-multiple-objects-of-same-class/ Share on other sites More sharing options...
ignace Posted February 25, 2011 Share Posted February 25, 2011 class Cube { private $cubes = array(); public function addCube(Cube $cube) { $this->cubes[] = $cube; return $cube; } public function addCubes(array $cubes) { foreach($cubes as $cube) { $this->addCube($cube); } return $this; } } $cube = new Cube(); $cube->addCube(new Cube())->addCube(new Cube())->addCubes(array(new Cube(), new Cube(), new Cube(), new Cube())) print_r($cube); You could take a look at the Composite Pattern Quote Link to comment https://forums.phpfreaks.com/topic/228774-oop-an-object-with-an-array-containing-multiple-objects-of-same-class/#findComment-1179477 Share on other sites More sharing options...
fanus.link Posted February 25, 2011 Author Share Posted February 25, 2011 wow. thats perfect. thanks a million! Quote Link to comment https://forums.phpfreaks.com/topic/228774-oop-an-object-with-an-array-containing-multiple-objects-of-same-class/#findComment-1179481 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.