Question

I am trying to keep an open pgsql database connection in a property of an object.

The database connection is transfered to the object as a paramter of the constructor and saved in a property. Later a function of the class that needs the databse connection is called, and reads from the property. However it somehow is not read as a working DB connection.

I checked the DB Connection outside of the object, and it is still open there, after the function in the class is called.

Why does the resource seem to close in the object, and is there any way I can keep it open?

Code example:

public class test{

    public function __construct($db_conn){
        $this->db_conn = $db_conn;
        var_dump($this->db_conn);      // this returns resource(4) of type (pgsql link)
    }


    public function testDBConn(){           
        var_dump($this->db_conn);          //this returns resource(4) of type (Unknown)   
        $result = pg_query($this->db_conn, 'SELECT * FROM tbl_test');
    }
}

Update: The class I'm using actually extends another class. This causes an "PHP Fatal error: Cannot assign by reference to overloaded object" error, if I try set the property by reference. If my class doesn't extend another class, the set the property by reference approach works great.

Is there any way to get it working in an overloaded class?

No correct solution

OTHER TIPS

This will work if you set the property by reference.

public function __construct(&$db_conn){
    $this->db_conn = &$db_conn;    // note the &
    var_dump($this->db_conn);
}

To make this abundantly clear, here 2 testcases:

class reftest {
    public $test = NULL;
    public function __construct(&$test) {
        $this->test = &$test;
    }
}

$test = 'a';
echo "\$test before: $test<br>";
$reftest = new reftest($test);
echo "\$test after: $test and " . $reftest->test . "<br>";
$test = 'b';
echo "\$test after: $test and " . $reftest->test . "<br>";

output:

$test before: a
$test after: a and a
$test after: b and b

if you miss one of the & symbols you get the behavior you describe:

class reftest {
    public $test = NULL;
    public function __construct(&$test) {
        $this->test = $test;
    }
}

$test = 'a';
echo "\$test before: $test<br>";
$reftest = new reftest($test);
echo "\$test after: $test and " . $reftest->test . "<br>";
$test = 'b';
echo "\$test after: $test and " . $reftest->test . "<br>";

output:

$test before: a
$test after: a and a
$test after: b and a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top