Too few arguments to function Db::__construct(), 0 passed in

i have 3 pages one for connect the DB

class Db{

private $dbUserName ="root";
private $dbName = "oop";
private $dbPas = "";
private $dbHost = "127.0.01";

public function __construct($dbUserName, $dbName, $dbPas, $dbHost)
    $this->dbUserName = $dbUserName;
    $this->dbName = $dbName;
    $this->dbPas = $dbPas;
    $this->dbHost = $dbHost;

    $con = new PDO("mysql:host= $dbHost; $dbUserName,$dbName,$dbPas");
    return $con ;

the 2 is

class User extends Db{
protected function getAllUser(){

    $sql = "SELECT * FROM user";
    $result = $this->connect()->query($sql);

    $count = $result->rowCount();
    // check if there'r date in the db
    if($count > 0){
        while($row = $result->fetchAll() ){
            $data[] = $row;
        return $data;



the 3 is

class ViewUser extends User{

public function ViewAllUser (){

    $datas = $this->getAllUser();

    foreach($datas as $data){
        //echo the db rows
        echo $data['uid']."</br>";
        echo $data['pas']."</br>";



when I try to run them on another page:

    include 'Db.php';
    include 'User.php';
    include 'ViewUser.php';

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">

        $users = new ViewUser();


i get a error:

Uncaught ArgumentCountError: Too few arguments to function Db::__construct(), 0 passed in /Users/mohamedelmasry/Documents/websites/oop/test.php on line 18 and exactly 4 expected in /Users/mohamedelmasry/Documents/websites/oop/Db.php:18 Stack trace: #0 /Users/mohamedelmasry/Documents/websites/oop/test.php(18): Db->__construct() #1 /Users/mohamedelmasry/.composer/vendor/laravel/valet/server.php(128): require(‘/Users/mohamede…’) #2 {main} thrown in /Users/mohamedelmasr

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Your base class constructor expects 4 arguments:

class Db{


    public function __construct($dbUserName, $dbName, $dbPas, $dbHost)

So you can not create the child class without parameters.
You need to either do:

$users = new ViewUser('root', 'dbname', 'pass', 'host');

Or put defaults into constructor declaration:

public function __construct($dbUserName='root', $dbName='db', $dbPas='pass', $dbHost='host')

But in general, the inheritance is misused here. You’d better have a separate Db class to manage DB and use it as a component inside your other classes (use composition instead of inheritance).

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply