PHP构造函数返回通过引用传递的对象

时间:2013-07-07 20:59:42

标签: php oop reference constructor

我正在开发一个PHP类,它将获取另一个类并以某种方式返回它,显然构造函数不能返回值,所以我看着通过引用传递,这就是我得到的:

<?php
class Example {
    public function __construct($name,&$var){
        //This registers the class in my system (I know this part works)
        IceTray::$Registry->registerLibrary($name);
        //this fetches the object of the registered class above (I know it works)
        $var = IceTray::$Registry->Libraries->$name;
    }

我通过参考错误传递了吗?因为当我在我的项目中使用它时:

$test = 0;
$lib = new Example('ClassName', $test);
$test->testing();

$ Test是我希望存储对象的变量,构造函数的第一个参数是要注册的类的名称,并分配给通过引用传递的变量,这是第二个参数。下一行在请求的类名称中称为方法,但它不起作用。

没有任何错误或任何事情,我再次通过参考概念我可能会做错事。非常感谢任何帮助,提前谢谢!

1 个答案:

答案 0 :(得分:0)

class Example {
    public $var = null;
    public function __construct($name){
        //This registers the class in my system (I know this part works)
        IceTray::$Registry->registerLibrary($name);
        //this fetches the object of the registered class above (I know it works)
        $this->var = IceTray::$Registry->Libraries->$name;
    }
}

$lib = new Example('ClassName');
$lib->var->testing();

为什么要伤害自己而不使用调用属性来返回您需要的内容?