2012-07-08 3 views
0

db_class.phpPHP 오류 호출()

<?php 
class db_mysql 
{ 
    private $dbhost; 
    private $dbusername; 
    private $dbpassword; 
    private $db; 

    //Class is called with all parameters to make a successful connection. 
    // 
    function __construct($dbhost,$dbusername,$dbpassword,$db) 
     { 

     global $dbh; 
     try { 
       $dbh = new PDO("mysql:host=$dbhost;dbname=$db", $dbusername, $dbpassword); 
      foreach($dbh->query('show tables;') as $row) { 
      print_r($row); 
      } 
      //$dbh = null; 
     } catch (PDOException $e) { 
      print "Error!: " . $e->getMessage() . "<br/>"; 
      die(); 
     } 

     } 

    //Function to execute a query in the database and return result in a array 
    // 
    function db_mysql_query($queryst) 
    { 
     foreach($dbh->query($queryst) as $row) { 
      print_r($row); 
      } 
    } 

} 

의 index.php는 :

<?php 
include 'db_class.php'; 

$db_m = new db_mysql('localhost','root','','arsaas'); 
$db_m->db_mysql_query('show tables;'); 
?> 

실행 index.php에 다음과 같은 오류를 제공합니다 : 공지 사항 : 정의되지 않은 변수 : 32 행의 C : \ xampp \ htdocs \ srry \ db_class.php에있는 dbh

치명적 오류 : C : \ xampp \ htdocs \ srry의 개체가 아닌 멤버 함수 query()를 호출하십시오. \ db_class.php on line 32

dbh가 인스턴스 생성되고 클래스 생성자에서 전역 변수로 선언 될 때 dbh가 정의되지 않은 변수라고 말하는 이유는 무엇입니까?

도움을 주시면 감사하겠습니다. 미리 감사드립니다.

AR

+0

특정 오류 메시지 중 이해하기 어려운 부분은 무엇입니까? – hakre

답변

2

db_mysql_query 방법에 따라서 작동하지 않는 개체에 대한 방법 쿼리를 호출하려고 변수 $ DBH를 정의하지 않습니다. PDO 객체 ($ dbh)를 생성자의 db_mysql 객체에 저장하고 db_mysql_query를 호출 할 때 사용할 수 있습니다. 데이터베이스 연결을 하나만 사용하려는 경우 db_mysql 클래스에서 싱글 톤 패턴을 사용하는 것이 좋습니다. http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html

+0

감사합니다. 그러나 GLOBALS 배열을 참조하는 다른 대안보다 조금 더 복잡합니다. – user1510223

+1

싱글 톤은 단지 글로벌입니다. 당신은 OP의 문제에 대한 해결책으로 환상적인 글로벌 서면을 제안하고 있습니다. 글로벌/싱글 톤을 사용하지 않으면 여기로 갈 수 있습니다. –