Pedro Henrique Pedro Henrique - 1 year ago 76
PHP Question

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, wich has its Itens, wich refer to their Order, wich 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.

Answer Source

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();

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download