Yii Framework Forum

Two objects contain each other. Is it OK?


(Maxim) #1

Hello. Is it good practice to have two objects (classes) which contain each other as class properties?

Say:




class Country

{

    public $capital;

}


class City

{

    public $name;

    public $country;

}


$uk = new Country();

$london = new City();

$london->country = $uk;

$uk->capital = $london;






The question is theoretical and isn’t related to any framework. Technically it seems OK because in memory there will be just pointers to respective objects. Is it good practice or should I use another apporach?


(Alexander Makarov) #2

It’s OK but take into account that it would create circular references. Till both objects are unset memory won’t be freed.