Where is the "Unable to access empty property" fatal error in a PHP class function?

What is wrong with this code?

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

Error:

Fatal error: Unable to access empty property in C: \ xampp \ htdocs \ jordan_pagaduan \ class.php on line 15.

+3
source share
1 answer

To access class-property from within a class method, you should use $this->propertyName, not $this->$propertyName.

This means that your method user_input()should be written as follows:

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

(you may need to make the same modification elsewhere)


, , $this->db_user ; , , :

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

$this->db_user - null; mysql_connect - ODBC, .

( ), , ODBC , : .)

+14

Source: https://habr.com/ru/post/1742866/


All Articles