2017-05-19 71 views
2

我有3頁一個用於連接DB太少參數化功能數據庫:: __建設(),0通過在

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 ; 
} 

2是

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; 
    } 

} 

} 

的3

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>"; 
    } 

} 

} 

當我嘗試在其他頁面上運行它們時

<?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> 

我收到一個錯誤未捕獲ArgumentCountError:函數太少參數Db :: __構造(),0在/Users/mohamedelmasry/Documents/websites/oop/test.php在第18行傳入,並且在/ Users中恰好爲4 /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}拋出/ Users/mohamedelmasr

+0

我固定那樣。 class Db {0} {0}私人$ dbUserName =「root」; private $ dbName =「oop」; private $ dbPas =「」; private $ dbHost =「127.0.0.1」; protected function connect(){ $ this-> dbUserName =「root」; $ this-> dbName =「oop」; $ this-> dbPas =「」; $ this-> dbHost =「localhost」;我們可以通過下面的例子來說明如何使用dbOutName來創建數據庫:$ db = $ db-> return $ con; } } –

回答

1

您的基類構造函數需要4個參數:

class Db{ 

... 

    public function __construct($dbUserName, $dbName, $dbPas, $dbHost) 
    { 
     ... 
    } 

所以你不能創建沒有參數的子類。 你需要做的兩種:

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

或把默認爲構造函數聲明:

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

但在一般情況下,繼承這裏濫用。您最好有一個單獨的Db類來管理數據庫,並將其用作其他類中的組件(使用組合而不是繼承)。