douba1498 2014-12-05 15:45
浏览 81
已采纳

Php在构造函数中创建对象[关闭]

I have two php classes, in two files.

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

db contains:

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 contains :

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

in 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();
}   

What I am doing wrong?
The includes are ok, I tested them. But why variables of sql Object are empty??? thank you.

  • 写回答

3条回答 默认 最新

  • dongliang9576 2014-12-05 17:01
    关注

    $con is a property of the class not a variable, you refer to it by using keyword $this:

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

    change to:

    $this->con = $dataBase->getConnection(); //CORRECT
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?