Im trying to extend a simple database class.
<?php
class Database {
public $db;
public function __construct($db)
{
$this->db = $db;
}
public function insert($table, $row, $value)
{
$query = $this->db->prepare('INSERT INTO ? (?) VALUES (?)');
$query->bindValue(1, $table);
$query->bindValue(2, $row);
$query->bindValue(3, $value);
$query->execute();
}
}
?>
And this is my main class that extends the previous class:
<?php
class AdminAccount extends Database {
public function setValues($table, $row, $value)
{
$this->insert($table, $row, $value);
}
}
?>
And this is what the $db variable is...
$hostname = 'localhost';
$database = 'mydb';
$username = 'root';
$password = 'root';
$db = new PDO("mysql:host=" . $hostname . ";dbname=" . $database, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then i include, instantiate etc..
<?php
require_once('includes/settings.php');
require_once('includes/connect.php');
require_once('lib/class.database.php');
require_once('lib/class.adminaccount.php');
$database = new Database($db);
$adminaccount = new AdminAccount();
$adminaccount->setValues('tasklist', 'creator', 'Zet');
?>
For some reason I get this error:
Warning: Missing argument 1 for Database::__construct(), called in /Applications/MAMP/htdocs/admin/extend.php on line 14 and defined in /Applications/MAMP/htdocs/Admin/lib/class.database.php on line 7
Notice: Undefined variable: db in /Applications/MAMP/htdocs/Admin/lib/class.database.php on line 9
Why is this? Everything works just fine when I connect to the database WITHOUT EXTENDING.
I see what is going on now.
You are extending Database in AdminAccount which includes the Database constructor. Therefore you need to include $db when you are instantiating AdminAccount too or you need to write a new __construct() in AdminAccount.
Just from looking at your code, I don't see the point of you extending Database. You should just pass $database to AdminAccount or instantiate Database in AdminAccount, but if you really do need to extend Database then the solution would be:
$adminaccount = new AdminAccount($db);
$db
in your last piece of code is undefined. It hasn't been set. Constructor of Database class expects a value.