PHP5: reference to objects

I am writing multiple object classes in php that can point to each other using the repository class (to avoid too many database queries using the local object repository):

class Foo
{
    public $fooId;
    public $bar;
    function __construct($entity_id)
    {
        /**
        * Some Database stuff to get Foo object based on $entity_id
        **/
        $this->bar = Repository::get('Bar', $databaseStuff->barId);
    }
}

class Bar
{
    public $foo;
    function __construct($entity_id)
    {
        /**
        * Some Database stuff to get Bar object based on $entity_id
        **/
        $this->bar = Repository::get('Bar', $databaseStuff->barId);
    }
}

class Repository
{
    private static $entities = [];
    /**
     * @param string $entity_name
     * @param int $entity_id
     * @return mixed
     */
    public static function &get($entity_name, $entity_id)
    {
        $entity_name = ucfirst(strtolower($entity_name));
        if(!isset(self::$entities[$entity_name][$entity_id]))
        {
            self::$entities[$entity_name][$entity_id] =& $entity_name($entity_id);
        }
        return self::$entities[$entity_name][$entity_id];
    }
}

$foo = new Foo(1337);

      

The problem is that I get a kind of timeout / stack overflow, probably due to the fact that it $foo->bar

is a reference to the Bar object, but $bar->foo

is a reference to a Foo object, etc.

  • I didn't forget to declare that my function returns a reference using & get (), am I right?
  • My class is instantiated using the = & operator.

What could be wrong in my code (or my logic)? Thank.

+3


source to share


1 answer


If I see it correctly, the Bar constructor is trying to create a new Bar.
I believe that this nested build will never end. Its the same, for example, when a function calls itself recursively and cannot exit.
The script won't even come to checkout in the repository.

Ever tried xdebug? This can show the problem pretty quickly.



And btw there is a possibly bad copy / paste. The comment in the Foo class does not match the line it is on. And you set $ this-> bar to the Bar class, but only the $ foo class variable is declared.

+1


source







All Articles