加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP类函数中的致命错误“无法访问空属性”在哪里?

发布时间:2020-12-13 22:12:31 所属栏目:PHP教程 来源:网络整理
导读:这段代码有什么问题? ?phpclass users { var $user_id,$f_name,$l_name,$db_host,$db_user,$db_name,$db_table; function users() { $this-$db_host = 'localhost'; $this-$db_user = 'root'; $this-$db_name = 'input_oop'; $this-$db_table = 'users'; }
这段代码有什么问题?

<?php

class users {

  var $user_id,$f_name,$l_name,$db_host,$db_user,$db_name,$db_table;

  function users() {
      $this->$db_host = 'localhost';
      $this->$db_user = 'root';
      $this->$db_name = 'input_oop';
      $this->$db_table = 'users';
  }

  function userInput($f_name,$l_name) {
      $dbc = mysql_connect($this->db_host,$this->db_user,"") or die ("Cannot connect to database : " .mysql_error());
      mysql_select_db($this->db_name) or die (mysql_error());
      $query = "insert into $this->db_table values (NULL,"$f_name","$l_name")";
      $result = mysql_query($query);
      if(!$result) die (mysql_error());

      $this->userID = mysql_insert_id();

      mysql_close($dbc);

      $this->first_name = $f_name;
      $this->last_name = $l_name;
  }

  function userUpdate($new_f_name,$new_l_name) {
      $dbc = mysql_connect($this->db_host,"") or die (mysql_error());
      mysql_select_db($this->db_name) or die (mysql_error());

      $query = "UPDATE $this->db_table set  = "$new_f_name","$new_l_name" WHERE user_id = "$this->user_id"";
      $result = mysql_query($query);

      $this->f_name = $new_f_name;
      $this->l_name = $new_l_name;
      $this->user_id = $user_id;

      mysql_close($dbc);
  }

  function userDelete() {
      $dbc = mysql_connect($this->db_host,"") or die (mysql_error());
      mysql_select_db($this->db_name) or die (mysql_error());

      $query = "DELETE FROM $this->db_table WHERE $user_id = "$this->user_id"";

      mysql_close($dbc);
  } 
}
?>

错误是:

Fatal error: Cannot access empty property in C:xampphtdocsjordan_pagaduanclass.php on line 15.

解决方法

要从类的方法内部访问 class-property,您必须使用$this-> propertyName,而不是$this-> $propertyName.

这意味着你的user_input()方法应该这样写:

function user_input() {
    $this->db_host = 'localhost';
    $this->db_user = 'root';
    $this->db_name = 'input_oop';
    $this->db_table = 'users';
}

(您可能需要对其他地方进行相同的修改)

根据您所写的内容,$this-> db_user永远不会被设置;以及以后使用时:

$dbc = mysql_connect($this->db_host,"")

$this-> db_user为null;这意味着mysql_connect将使用default value – 在您的情况下,似乎是ODBC,从错误消息判断.

(与其他属性相同 – 但我以此为例,因为ODBC默认值出现在您发布的错误消息中:它是最明显的选择.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读