title: Infinty loop in constuctor - Creating the same istances of related objects
body: <p>I got stuck in an endless loop creating the same objects over and over in the models.</p>
  <p>But from the beginning:</p>
  <p>I have two related models, lets call <code>A</code> and <code>B</code></p>
  <p><code>A</code> could has many <code>B</code> and <code>B</code> belongs to one <code>A</code>.</p>
  <p>And since model <code>B</code> refers to the fields of <code>A</code>, I added it as protected property to avoid creating new object when calling <code>B</code> method related with <code>A</code> fields.</p>
  <p>The constuctor of <code>B</code> looks like:</p>
  <pre><code>public function __construct(int $id = null)
  {
      parent::__construct($id);
  
      $a = $this-&gt;get('a_id'); 
      if ($a) {
          $this-&gt;a = new A($a);
      }
  }
  </code></pre>
  <p>and <code>A</code>:</p>
  <pre><code>public function __construct(int $id = null)
  {
      parent::__construct($id);
  
      $this-&gt;date = new CarbonPL($this-&gt;get('date'));
      $this-&gt;initB();
  }
  </code></pre>
  <p>But then I realized that calling initB() creates again the same instance o B with creating the same A and so on forever</p>
  <pre><code>private function initB()
  {
      if (!$this-&gt;isReferenced()) { // Checks wheter is instance exists in DB
          return;
      }
      $query = B::getIDQuery();
      $query .= ' WHERE is_del IS FALSE';
      $query .= ' AND a_id = ' . $this-&gt;id;
  
      $ids = Helper::queryIds($query);
  
      foreach ($ids as $id) {
          $this-&gt;B[] = new B($id);
      }
  }
  </code></pre>
  <p>I need that object of A contains loaded of B and vice verse, because a lot of B refer to A field and vice versa, but how to prevent yourself from such an endless loop.</p>
  <p>I quickly got the idea of an extra parameter in <code>B</code> which would be <code>A</code>, and if it were, I wouldn't have to reuse the constuctor. But I don't really like this solution because of the second parameter and I was wondering how to solve it in a different (better) way, preferably so that you can still only enter the identifier.</p>
  <p><code>B</code> conctructor after that fix:</p>
  <pre><code>public function __construct(int $id = null, A $a = null)
  {
      parent::__construct($id);
  
      if ($a) {
          $this-&gt;a = $a;
      } else {
          $a = $this-&gt;geti('a_id');
          if ($a) {
              $this-&gt;a = new A($a);
          }
      }
  }
  </code></pre>