Jump to content

OOP; An object with an array containing multiple objects of same class


fanus.link

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.