简体   繁体   中英

How to return a class variable as a reference (&/ampersand) in PHP?

This is sample of my code.

class SomeClass extends SomeOtherClass
{

    function __construct($input)
    {
        parent::__construct($input);
        $this->conn = new mysqli('a','b','c','d');
    }

    function getConnection()
    {
        return &$this->conn;
    }

}

My main object is that i want to return the MySQLi connection by referencing it instead of creating another MySQLi class.

It's:

function &getConnection()
{
   return $this->conn;
}

and when calling:

$conn = &$instance->getConnection();

That's how to return variables by reference in general, but for resource type variables you don't need to.

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