I can't seem to find a answer for that, maybe somebody here can help me.
I'm trying to pass in a database
connection in the construct
of my class
but i'm getting an error "Missing argument 1 for item::__construct() "
,
I'v tried setting it with a setter method it works perfectly, so i know the variable
with the database
connection is right.
I'v tried to pass in the constructor
plain text, like $item = new item('abc')
and then I'm getting it perfectly.
The reason I want it in the constructor is because its a database
connection so I'll always need it.
In index.php
the code is not in a class so the problem cannot be the scope.
Here is the code. index.php.
$dbh = new dbh;
$item = new item($dbh);
item.php
<?php
class item{
protected $costumerId;
private $databaseConnection;
public function __construct(dbh $database) {
$this->databaseConnection = $database;
var_dump($this->databaseConnection);
}
public function setCostumer($costumerId) {
$this->costumerId = $costumerId;
}
public function getItems(){
try {
$query = 'SELECT * FROM items WHERE costumerId = :costumerId';
//Execute
$this->result = $this->databaseConnection->getRows($query, array(':costumerId' => $this->costumerId),'item');
return $this->result;
}
catch(Exception $e) {
var_dump($e->getMessage());
}
}
}
?>
Thanks in advance.
Edit this is the database connection class.
class dbh {
public $isConnected;
public $connection;
public function __construct()
{
try {
$this->connection = new PDO ('mysql:host=localhost;dbname=test','username','password');
$this->isConnected = true;
var_dump($this->connection);
}
catch(PDOException $e) {
$this->isConnected = false;
throw new Exception ($e->getMessege());
}
}
public function getRows($query, $params=array(), $class = 'assoc') {
try {
$stmt = $this->connection->prepare($query);
$stmt->execute($params);
if($class != 'assoc'){
$stmt->setFetchMode(PDO::FETCH_CLASS, $class);
return $stmt->fetchall();
}
else {
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt->fetchall();
}
}
catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
}
EDIT
i see now that im only getting the error when the next statment is there, i mean if i comment out the next statment after $item = new item($dbh)
that is $items->setCostumer(6);
im not getting the error,
EDIT:
ok i found that when i call the function getItems, or more spacificly the line $this->result
is causing the error. but i still dont know why