简体   繁体   English

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

[英]PHP constructor return object with pass by reference

I'm working on a PHP class that will fetch another class and somehow return it, obviously constructors can't return values so I was looking at passing by reference and this is what I got: 我正在研究一个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;
    }

Am I passing by reference wrong? 我通过引用传递的错误吗? Because when I use this in my project: 因为当我在项目中使用它时:

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

$Test is the variable I wish to store the object in, the first argument of the constructor is the name of the class to register and assign to the variable passed by reference which is the second argument. $ Test是我希望存储对象的变量,构造函数的第一个参数是要注册并分配给通过引用传递的变量(第二个参数)的类的名称。 The next line is called a method inside the requested class name, but it's not working. 下一行在所请求的类名内称为方法,但它不起作用。

No errors or anything, again I'm new to the passing by reference concept maybe I'm doing something wrong. 没有错误或其他任何内容,同样,我还是引用参考概念的新手,也许我做错了什么。 Any help is very much appreciated, thanks in advance! 非常感谢您的任何帮助,在此先感谢您!

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

Why hurt yourself and not use calls properties to return what you need? 为什么要伤害自己而不使用调用属性返回需要的内容?

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

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