在php中'无法访问空属性'错误

时间:2015-03-31 09:21:17

标签: php oop mysqli php-5.5

我很困惑,我在下面的PHP代码中犯了错误。虽然,我看了很多时间在我的代码上,但无法找到我收到此错误的原因'无法访问空属性'

class DBTest{
//declare variables
private $servername = "localhost";
private $username = "root";
private $password = "";
private $database = "avn_test";
private static $conn;
private $results;

//constructor
public function __construct(){
self::$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
} //close constructor

public function executeQuery($query='') {
if(!empty($query)){
$query = self::$conn->real_escape_string($query);

**以下行错误:**

$this->results = self::$conn->query($query) or die("Error in database connection".self::$conn->$error);

if( $this->results->num_rows > 0 ) {
$rowqry = array();
while($row = $this->results->fetch_object()) {
$rowqry[]= $row; } //close of while
$rarray['returnvar'] = $rowqry;
return $rarray;
} else {
return false; } // close of else
}//close of top if
else
return false;
} //close of function

function __destruct(){
self::$conn->close();}
} //close of class

//create an object of class DBTest
$test = new DBTest();
$q= "select * from test";
$tmp = $test->executeQuery($q);

if($tmp){
foreach($tmp as $key => $value){
echo $value;}
}
else
echo 'tmp var is empty';

2 个答案:

答案 0 :(得分:2)

在这一行:

$this->results = self::$conn->query($query) or die("Error in database connection".self::$conn->$error);

self::$conn->$error替换为self::$conn->error

访问静态属性时需要$,但实例属性不需要。{/ p>

答案 1 :(得分:0)

$函数

中不需要$conn
self::$conn replace with self::conn
                           ^^^^^^