调用父和子构造函数

时间:2015-01-11 04:02:38

标签: php constructor parent-child

我的一些类在父级和子级中都有构造函数。我怎样才能运行两个构造函数?

家长班:    

include 'c:/wamp/www/mvc/include/connect.php';
class Database
{

    protected $mysqli;
    protected $exc;

    function __construct(mysqli $db)
    {
        mysqli_set_charset($db,'utf8');
        $this->mysqli = $db;
    }

<?php

子类:( LoginClass)

<?php


class Login extends Database {
    private $username;
    private $password;

    function __construct(mysqli $db, $username, $password)
    {
        parent::__construct($db);
        $this->setData($username, $password);
        $this->getData();
    }
    function setData($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }


    function getData()
    {
        $result = $this->mysqli->query("SELECT * FROM anvandare WHERE anvandarnamn = '$this->username;'  AND losenord =  '$this->password'");

        $count = $result->num_rows;

        if($count>0)
        {
            return true;
        }
        else
        {
            throw new Exception("Username or Password incorrect. Please try again");
        }

    }

LoginController.php

<?php
//LoginController
if($_POST)
{
    if(isset($_POST['submit']) AND $_POST['submit'] == "login")
    {
        $username = $_POST['username'];
        $password = $_POST['password'];
        try
        {
            include '../model/Login.php';
            $login = new Login($db ,$username, $password);

            if($login == TRUE)
            {
                session_start();
                $_SESSION['username'] = $username;
                header("Location:../index.php");
            }
        }
        catch (Exception $exc)
        {
            echo $exc->getMessage();
        }
    }
}

我尝试在子构造函数中调用parent::__construct($this->mysqli);,但不知何故它没有工作。

1 个答案:

答案 0 :(得分:0)

它可能不起作用,因为父构造函数需要传递mysqli的实例。但是,以下签名应该有效:

require_once __DIR__ . '/Database.php';

class Login extends Database
{
    function __construct(mysqli $db, $username, $password)
    {
        parent::__construct($db);
        $this->setData($username, $password);
        $this->getData();
    }
}
相关问题