繁体   English   中英

PHP5:对象引用

[英]PHP5: Objects reference

我正在写一些php中的实体类,它们可能指向彼此之间的存储库类(以避免使用本地实体存储库查询过多的数据库):

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);

问题是我得到了一种超时/堆栈溢出可能是因为$foo->bar是对Bar对象的引用,但是$bar->foo是对Foo对象的引用等...

  • 我没有忘记声明我的函数使用&get()返回引用,我是对的吗?
  • 我的类用=&运算符实例化。

我的代码(或我的逻辑)可能有什么问题? 谢谢。

如果我看对了,Bar的构造函数会尝试创建新的Bar。
我想这样一个嵌套的构造永远不会结束。 它是相同的,例如当一个函数递归调用自己而无法退出时。
该脚本甚至不会写入Repository。

有没有试过xdebug? 这可能会很快显示问题。

顺便说一句,有可能复制/粘贴。 Foo类中的注释与使用它的行不匹配。 你在类Bar中设置$ this-> bar,但只声明了类变量$ foo。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM