I'm writing some entities class in php, that may point between each other with a repository class (to avoid to query too much the database using a local entity 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 sort of timeout/stack overflow probably due to the fact of $foo->bar is a reference to a Bar object, but $bar->foo is a reference to a Foo object, etc...
- I did not forgot to declare my function to return a reference using &get(), am i right?
- My class is instantiated with =& operator.
What could be wrong in my code (or in my logic) ? Thanks.
serialize()that, it will produce output undefinitely until it either run out of memory or time. The garbage collector (or at least I think it is the gc that causes that) will also have some nasty performance issues and eventual crashes. I've had plenty of experience with that lately, and decided its best to avoid doing circular references in PHP.get()at any point as far as I can tell. You should be calling&Repository::get()instead of justRepository(). Functions that return a reference must be called with&too in order to work. However, if you are returning an object, you can drop the whole reference thing. Objects are already implicitly passed by reference. To pass a copy of an object in PHP you must explicitly say it, withclone $object.