3

Is it bad practice or have a significant performance impact to have a cyclical reference? e.g., add object A as property of object B and then Object B as property of Object A?

An example:

<?php 

class Object_A {

    public function __construct() {
        $this->b = new Object_B( $this );       
    }

    public function get_b() {
        return $this->b;
    }

}

class Object_B {

    public function __construct( Object_A $a ) {
        $this->a = $a;
    }
}

This answer seems to be similar, but for C#.

Community
  • 1
  • 1
  • 1
    It isn't always possible to avoid it, but causes enough problems that you should try to avoid it if at all possible – Mark Baker Aug 24 '15 at 13:22
  • This is certainly a design smell. I cannot think of an example where this would be necessary, but it seems that you have. Are you just curious? If this is real work, ask your colleagues. I would try to avoid this if at all possible. – Mawg says reinstate Monica Aug 24 '15 at 13:31

1 Answers1

3

For a more general discussion about cyclic references see What's wrong with circular references? on the programmers stackexchange site. But keep in mind the question explicitly states

I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.

PHP implements a garbage collector fully capable of collecting cycles since version 5.3.

Performance considerations are discussed under Garbage Collection - Performance Considerations in the manual.

Community
  • 1
  • 1
VolkerK
  • 95,432
  • 20
  • 163
  • 226