$db_user = 'root'; $this->$db_name = 'input_oo-6ren">
gpt4 book ai didi

php - PHP类函数中的 fatal error "Cannot access empty property"在哪里?

转载 作者:可可西里 更新时间:2023-10-31 23:57:51 26 4
gpt4 key购买 nike

这段代码有什么问题?

<?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);
}
}
?>

错误是:

Fatal error: Cannot access empty property in C:\xampp\htdocs\jordan_pagaduan\class.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, "")

$this->db_user 为空;这意味着 mysql_connect将使用 default value -- 从错误消息来看,在您的情况下,它似乎是 ODBC

(与其他属性相同 - 但我以这个为例,因为 ODBC 默认值出现在您发布的错误消息中:它是最显而易见的选择。)

关于php - PHP类函数中的 fatal error "Cannot access empty property"在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2715610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com