其中是致命错误“无法访问空属性”在PHP类中的函数? [英] where is the fatal error "Cannot access empty property" in the PHP class function?
问题描述
此代码有什么问题?
<?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, $this->db_user, "") 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, $this->db_user, "") 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);
}
}
?>
错误是:
致命错误:无法在第15行访问C:\ xampp\htdocs\jordan_pagaduan\class.php中的空属性。
Fatal error: Cannot access empty property in C:\xampp\htdocs\jordan_pagaduan\class.php on line 15.
推荐答案
要访问 class-property 从类的方法内部,必须使用 $ this-> propertyName
,而不是 $ this-> $ propertyName
。
To access a class-property from inside a method of a class, you must use $this->propertyName
, and not $this->$propertyName
.
这意味着您的 user_input ()
方法应该写成这样:
Which means your user_input()
method should be written like this :
function user_input() {
$this->db_host = 'localhost';
$this->db_user = 'root';
$this->db_name = 'input_oop';
$this->db_table = 'users';
}
(您可能需要对其他地方进行相同的修改)
(you might have to do the same modification to other places)
根据您撰写的内容, $ this-> db_user
从不设置; ,以后使用时:
With what you have written, $this->db_user
is never set ; and, later, when using this :
$dbc = mysql_connect($this->db_host , $this->db_user, "")
$ this-> db_user
为null;这意味着 mysql_connect
将使用默认值 - 在您的情况下,看起来是 ODBC
,从错误消息判断。
$this->db_user
is null ; which means mysql_connect
will use the default value -- which, in your case, appears to be ODBC
, judging from the error message.
- 但我把这个例子,因为 ODBC
默认值存在于您发布的错误消息:它是最明显的选择。)
(same thing with the other properties -- but I took this one as an example, as the ODBC
default-value was present in the error message you posted : it was the most obvious choice.)
这篇关于其中是致命错误“无法访问空属性”在PHP类中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!