Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: mały proble z OOP
Forum PHP.pl > Forum > PHP > Object-oriented programming
rychu123
  1. <?php
  2.  
  3. class db
  4. {
  5. private $host;
  6. private $user;
  7. private $pass;
  8. private $db_name;
  9. private $name_tabl;
  10.  
  11. public function __construct($HOST, $USER, $PASS, $DB_NAME, $NAME_TABL)
  12. {
  13. $this->host = $HOST;
  14. $this->user = $USER;
  15. $this->pass = $PASS;
  16. $this->db_name = $DB_NAME;
  17. $this->name_tabl = $NAME_TABL;
  18. }
  19.  
  20. private function connectDb()
  21. {
  22. $conn = new mysqli($this->host, $this->user, $this->pass, $this->db_name);
  23.  
  24. return $conn;
  25. }
  26.  
  27. private function queryTable()
  28. {
  29. return $this->connectDb->query('SELECT * FROM ' . $this->name_tabl);
  30. }
  31.  
  32. public function printNameColums()
  33. {
  34. $finfo = mysqli_fetch_fields($this->queryTable());
  35.  
  36. foreach ($finfo as $val)
  37. {
  38.  
  39. return "<th>" . $val->name . "</th>";
  40. }
  41.  
  42.  
  43. }
  44.  
  45. }
  46.  
  47. $a = new db('localhost', 'root', 'wsk123', 'nauka', 'pracownicy');
  48. echo $a->printNameColums();
  49.  
  50. ?>



Notice: Undefined property: db::$connectDb in C:\xampp\htdocs\ajax\showDb.php on line 29

Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\ajax\showDb.php on line 29
rad11
a nie
  1. return $this->connectDb()->query('SELECT * FROM ' . $this->name_tabl);


?
rychu123
sciana.gif
Tak zabrakło () . Dzięki
programista7
wiesz jaki jest teraz problem z Twoim kodem?

za kazdym razem gdy wywolujesz $this->connectDb() tworzysz obiekt polaczenia.

obiekt polaczenia stworz tylko raz i przypisz go do skladowej klasy a pozniej
zwracaj tylko ta skladowa:

  1. private function connectDb()
  2. {
  3. if (is_null($this->conn)) $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->db_name);
  4. return $this->conn;
  5. }
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2024 Invision Power Services, Inc.