问题
I have database class and constructor function this:
<?php
class Connection {
private $PDO;
function __construct() {
$username = 'root';
$password = 'password';
$PDO = new PDO('mysql:dbname=PROOV;host=localhost', $username, $password);
return $this->PDO;
}
}
?>
And the other class that extends it:
<?php
//$query = 'SELECT part_description FROM SparePartRequests LIMIT 100';
include_once 'connection.php';
class Proov extends PDO {
public function returnRows() {
$sth = $this->prepare('SELECT part_description FROM SparePartRequests LIMIT 100');
$sth->execute();
$result = $sth->fetch();
return $result;
}
}
$proov = new Proov(); // <- this is line nr 19...
?>
And it throws exception: Warning: PDO::__construct() expects at least 1 parameter, 0 given in /var/www/proov/proov1.php on line 19
How can i fix my problem? Thanks for any help!
Thanks for any help!
回答1:
But you're extending PDO
- not Connection
(and connection keeps a PDO
object - it does not extend it either). You need to decide which of these methods you want to use.
Perhaps this is what you want?
class Connection extends PDO {
public function __construct() {
$username = 'root';
$password = 'password';
parent::__construct('mysql:dbname=PROOV;host=localhost', $username, $password);
}
}
class Proov extends Connection { //We extend Connection - not PDO
public function returnRows() {
$sth = $this->prepare('SELECT part_description FROM SparePartRequests LIMIT 100');
$sth->execute();
$result = $sth->fetch();
return $result;
}
}
回答2:
Your derive your class Proov
from PDO
, therefore it also inherits its constructor, which in turn requires at least 1 parameter.
This is the constructor Proov
and PDO
both have:
public PDO::__construct() ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
Maybe you want to have the solution h2o provided, but I wouldn't recommend it. Ask yourself the question: "is Proov" a "Connection"? No, it is probably not, therefore I suggest using Dependency Injection:
class Proov {
private PDO $pdo;
public function __constructor($pdo) {
$this->pdo = $pdo;
}
public function returnRows() {
$sth = $this->pdo->prepare('SELECT part_description FROM SparePartRequests LIMIT 100');
}
}
This makes life simpler, especially when it comes to unit testing.
来源:https://stackoverflow.com/questions/19904852/pdo-constructs-expects-at-least-1-parameter-0-given