2011-12-15 113 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