【问题标题】:'cannot access empty property' error in phpphp中的“无法访问空属性”错误
【发布时间】:2015-06-04 13:53:09
【问题描述】:

我很困惑我在下面的 php 代码中出错的地方。虽然,我在我的代码上看了很多次,但找不到为什么我会收到这个错误 'cannot access empty property'

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("数据库出错 连接".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';

【问题讨论】:

  • 请用箭头或类似的方式指出您的错误行
  • 请在发生错误的那一行显示错误和黑暗或评论
  • 他也不需要这条线,因为连接会自动关闭。还有real_escape_string($query)??不仅不推荐使用此功能,而且使用它的方式完全错误。
  • 使用self::conn 而不是self::$conn
  • $conn 是静态的,亲爱的。那么,我怎样才能只使用 self::conn

标签: php oop mysqli php-5.5


【解决方案1】:

在这一行:

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

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

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

【讨论】:

    【解决方案2】:

    $conn 函数中不需要$

    self::$conn replace with self::conn
                               ^^^^^^ 
    

    【讨论】:

    • 我没查过,为什么__destruct不需要,其他地方需要呢?
    猜你喜欢
    • 2013-02-01
    • 1970-01-01
    • 2013-12-24
    • 2015-06-13
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    相关资源
    最近更新 更多