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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算