2

I have MysqliDb https://github.com/joshcam/PHP-MySQLi-Database-Class.

In my php class:

<?php 
require_once ('MysqliDb.php');

class Main{

protected $db;   


public function __construct()
{
    $this->db = new MysqliDb ('localhost', 'root', 'tuncay', 'db');
}

}

Class A extends Main{

public function __construct()
{   
    $this->db = MysqliDb::getInstance();
    echo $this->db->where("id", 5)->getOne('test')['text'];
}

}

$a = new A();

?>

Fatal error: Call to a member function where() on null in /.../db/index.php on line 21 where() function belongs MysqliDb.php

What is wrong? I got $this->db from Main class

I just want to keep DB connection in A class and use it.

Dharman
  • 30,962
  • 25
  • 85
  • 135
tuncayeco
  • 39
  • 7
  • hmm... if you haven't instatiated class Main before, then there's no DB connection to keep!? Maybe you want to do `parent::_construct()`? – Jeff Jul 29 '16 at 08:43

2 Answers2

3

Your Class A replace parent __construct. Try add

Class A extends Main{
  public function __construct()
  {   
     parent::__construct();
     $this->db = MysqliDb::getInstance();
     echo $this->db->where("id", 5)->getOne('test')['text'];
  }
  ...
}
Jeff
  • 6,895
  • 1
  • 15
  • 33
  • this line `$this->db = MysqliDb::getInstance();` doesn't make sense then, or is not needed. – Jeff Jul 29 '16 at 09:02
  • In A class I just want to use $this->db which is in Main class. If I use parent::_construct then connection will be repeated again. Is it normal? – tuncayeco Jul 29 '16 at 09:56
  • now your child construct just replace your parent construct and `$this->db = new MysqliDb ('localhost', 'root', 'tuncay', 'db');` dont uses. If your add `parent::__construct()` it will be uses. – Vladimir Goncharuk Jul 29 '16 at 10:02
  • what about memory?? each time calling the same function parent::_constract or connectDB ... or every time memory the same? – tuncayeco Jul 29 '16 at 11:27
1

Then you mean I can do like this:

<?php 
require_once ('MysqliDb.php');

class Main{

  protected  $db;   

   public function connectDB()
   {
    $this->db = new MysqliDb ('localhost', 'root', 'pass', 'db');
   }
}

Class A extends Main{
   public function __construct()
   {   
    $this->connectDB();
    echo $this->db->where("id", 5)->getOne('test')['text'];
   }
}

$a = new A();
?>

Is this normal? I mean, each time calling connectDB() function won't damage memory? or it will call every time the same part of memory ...?

tuncayeco
  • 39
  • 7