2013-10-15 3 views
0

객체의 속성에 열려있는 pgsql 데이터베이스 연결을 유지하려고합니다.PHP는 객체 속성에 리소스를 저장합니다.

데이터베이스 연결은 생성자의 매개 변수로 개체에 전송되고 속성에 저장됩니다. 나중에 databse 연결이 필요한 클래스의 함수가 호출되고 해당 속성에서 읽습니다. 그러나 어떻게 든 작동하는 DB 연결로 읽히지 않습니다.

개체 외부에서 DB 연결을 확인했으며 클래스의 함수를 호출 한 후에도 DB 연결이 여전히 열려 있습니다.

리소스가 개체에서 닫히는 것처럼 보이는 이유는 무엇이며 어떻게 열어 둘 수 있습니까?

코드 예제 :

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'); 
    } 
} 

업데이트 : 실제로 사용하고 클래스가 다른 클래스를 확장합니다. 이로 인해 "PHP 치명적인 오류 : 참조로 오버로드 된 객체에 할당 할 수 없습니다."라는 오류가 발생합니다. 참조로 속성을 설정하려고하면 오류가 발생합니다. 만약 내 클래스가 다른 클래스를 확장하지 않는다면, 참조에 의한 속성 접근법이 훌륭하게 작동합니다.

오버로드 된 클래스에서 작동하도록하는 방법이 있습니까?

답변

1

참조로 속성을 설정하면 작동합니다.

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>"; 

출력 : 당신이 행동을 얻을 & 기호 중 하나 놓칠 경우

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

는 당신이 설명 :

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

이 풍부하게 명확하고 여기에 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>"; 

출력 :

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