Pedro Henrique
Pedro Henrique

Reputation: 782

PHP class refer to second class which refer to first and so on

Sorry for the question title, I don't know how to name this issue, here it is:

I have two classes, Order and Item. An Order has Many Itens (array of Itens). An Item refer to its Order (Order object).

The problem is: The Order has its itens, each Item refer to its Order, which has its Itens, which refer to their Order, which refer to its itens, and so on...

The array hierarchy gets infinite.

Also I don't know how to properly construct the Order object. I have to create its itens and set them to the Order's Item array, but how can I set the Item's Order if the Order isn't yet constructed?

BTW, the data comes from database. Table Item has the Order_Id.

Upvotes: 0

Views: 53

Answers (1)

colburton
colburton

Reputation: 4715

Nothing fance to do, just:

class Order
{
    public $id;
    public $item;

    public function setItem(Item $item)
    {
        $this->item = $item;
    }
}

class Item
{
    public $id;
    public $order;

    public function setOrder(Order $order)
    {
        $this->order = $order;
    }
}

$order = new Order();
$item  = new Item();
$order->setItem($item);
$item->setOrder($order);

PHP saves only references to the objects, so there will be no endless recursion. Converting such data structures to json or something else, will require some sort of converter, but that is another topic.

Upvotes: 3

Related Questions