PDO __constructs expects at least 1 parameter, 0 given

烂漫一生 提交于 2019-12-25 05:03:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!