Php在构造函数中创建对象

时间:2014-12-05 15:45:14

标签: php

我有两个php类,分为两个文件。

.... db.php中 .... sql.php

db包含:

class DataBase {

private $link;
private $host;
private $username;
private $password;
private $database;

public function __construct() {
    print'<br>in constructor DB!<br>';
    $this->host     = 'xxxx';
    $this->username = 'xxxx';
    $this->password = 'xxxx';
    $this->database = 'xxxx';
    $this->connect();
}

public function connect() {
    $this->link = mysql_connect($this->host,$this->username,$this->password);
    if (!$this->link)   die('Could not connect: ' . mysql_error());
    mysql_select_db($this->database, $this->link);
}

public function getConnection() {
    return $this->link;
}

}

sql.php包含:

include 'db.php';

class SQL {

    public $dataBase;
    public $con;

    public function __construct() {
        $dataBase = new DataBase; 
        print 'database -> '.$dataBase; 
        $con = $dataBase->getConnection(); 
    }

    public function login($email, $pass) {
        $sql = "SELECT * FROM clienti WHERE email='".$email."' and pass= md5('".$pass."')";
        $result = mysql_query($sql, $con) or die(mysql_error());
        $row = mysql_fetch_assoc($result);
        if(!$row) return 'Email or password is incorrect.';
        return '';
    }
}

在login.php中

<?php
include 'include/sql.php';

$email  = $_GET['email'];
$pass= $_GET['pass'];

$error  = '';

if($email == '' || $pass== '') {
    $error = 'Email or password is empty.';
}
else {
    $sql = new SQL(); //if I print inside constructor, $con variable, is something like #3 resources
    echo $sql->con;  // but here is empty   ???
    $sql->login($email, $pass);
    $sql->close();
}   

我做错了什么? 包括没关系,我测试了它们。 但是为什么sql Object的变量是空的??? 谢谢。

3 个答案:

答案 0 :(得分:3)

$con是类的属性而不是变量,您可以使用关键字$this来引用它:

$con = $dataBase->getConnection(); //WRONG

更改为:

$this->con = $dataBase->getConnection(); //CORRECT

答案 1 :(得分:1)

你忘了()所以试试这个:

 $dataBase = new DataBase();

也可能是您遇到以下错误:

  

不推荐使用:mysql_connect():不推荐使用mysql扩展,将来会删除它:使用mysqli或PDO代替

所以我建议您将代码重写为PDOmysqli

顺便说一句:

对于错误报告,请使用:

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
?>

答案 2 :(得分:0)

您将$con列为私有,因此您无法从课外访问它,例如$sql->con。如果您需要像$sql->con一样使用它,请在SQL.php中更改它:

private $con;

到此:

public $con;

根据您的一条评论,您的问题可能仅仅是您需要在SQL类的方法中使用$this->con而不只是$con