简体   繁体   中英

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:

<?php
    include 'Db.php';
    include 'User.php';
    include 'ViewUser.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Oop</title>
</head>
<body>

     <?php
        $users = new ViewUser();
        $users->ViewAllUser();
     ?>

</body>
</html>

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM