【问题标题】:Calling both parent and child constructors调用父子构造函数
【发布时间】:2015-01-11 04:02:38
【问题描述】:

我的一些类在父类和子类中都有构造函数。如何运行这两个构造函数?

父类:

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

    }

登录控制器.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-&gt;mysqli);,但不知何故它不起作用。

【问题讨论】:

标签: php constructor parent-child


【解决方案1】:

它可能不起作用,因为父构造函数需要传递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();
    }
}

【讨论】:

  • 致命错误:在class Login extends Database中找不到类“数据库”
  • @David.J 如果您的 Database 类在另一个脚本中定义,您必须首先使用 require_once 包含该类。
  • 它适用于没有构造函数的类。只是那些构造函数不起作用
  • @David.J 这没有任何意义;您在这里提到的错误完全是另一个问题。
  • 更新了问题。我已经添加了我的 loginClass 和我的 loginController。如果您能检查一下,我将不胜感激。
猜你喜欢
  • 2018-01-31
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 2013-09-25
  • 2017-09-28
相关资源
最近更新 更多