E蜗牛 发表于 2010-3-4 23:03:12

CI代码中instantiate_class函数的作用


function &instantiate_class(&$class_object)
{
        return $class_object;
}
$objects[$class] =& instantiate_class(new $name());

上面的代码中为何不是直接使用
$objects[$class] =& new $name();

这样做的好处是什么

lamengao 发表于 2010-3-16 18:00:14

我想这是为了兼容php4

saturn 发表于 2010-3-16 19:41:46

这个问题提的非常好,说明楼主同学已经进入CI的源码分析阶段了,再接再厉,别忘了给大家分享更多的经验。

CI源码注释里面有写:
Returns a new class object by reference, used by load_class() and the DB class. Required to retain PHP 4 compatibility and also not make PHP 5.3 cry.

为了向下兼容PHP 4以及不让PHP 5.3蛋疼,初始化一个新类并返回其引用,用于load_class()和DB类。

如果你有从PHP 4迁移到PHP 5.x的经验,你可能会碰到这个问题:


function foo(&$var)
{
    $var++;
}

在PHP 5.3以上的版本中,它会如下错误:Call-time pass-by-reference has been deprecated.

原因在PHP官方手册上讲的很清楚,猛击这里:

As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

Hex 发表于 2010-3-16 22:57:59

顶!学习了!楼上不亏技术大牛~呵呵
页: [1]
查看完整版本: CI代码中instantiate_class函数的作用