简体   繁体   中英

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
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. 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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