2011-12-15 108 views
-1

我有兩個類:錯誤PHP和mysqli的

  1. database.php中
  2. query.php

還有就是我不明白的錯誤:

<?php 
    class database { 
     private $dbname = "class"; 
     private $dbuser = "soroush"; 
     private $dbpass = "passwprd"; 
     private $dbhost = "localhost"; 
     public $sql; 

     function __construct() { 
      $this->sql = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname) ; 
     } 
    } 

    class query extends database { 
     public static function GetStudentDetail() { 
      $query = $this->sql->query("SELECT * FROM user"); // error thrown here 
      $row = $query->fetch_assoc(); return $row; 
     } 
    } 

    var_dump(query::GetStudentDetail()); 
?> 

拋出的錯誤:

Fatal error: Using $this when not in object context in /var/www/html/lib/query.php on line 12

+0

sql = new mysqli($ this-> dbhost,$ this-> dbuser,$ this-> dbpass,$ this-> dbname); } } 類查詢數據庫延伸{ 公共靜態函數GetStudentDetail() { $查詢= $這個 - > SQL->查詢( 「SELECT * FROM用戶」); $ row = $ query-> fetch_assoc(); return $ row; } } var_dump(query :: GetStudentDetail()); ?> – 2011-12-15 01:57:38

回答

6

問題是因爲您使用靜態方法來訪問非靜態變量。
如果需要使用靜態調用所有這將需要一些變化,
更容易的解決辦法是實例化對象,並丟棄靜態調用,如: -

$query = new query(); <-- this will instantiate an object to $query and 
         <-- your class constructor will assign mysql connection 
         <-- to variable $sql 

// then 
$query->GetSt(); 

而在類聲明: -

class query extends db 
{ 
    public function GetSt() <-- remove the static