PHP类 - 在另一个函数中使用return

时间:2015-09-02 15:38:10

标签: php

我有一个带有2个函数DB_Connect()和LogIn()的PHP类。要使用LogIn(),我首先需要运行DB_Connect并获取$ CONN的返回值。我使用protected function DB_Connect() { $ROOT = dirname(__DIR__); include $ROOT."../core/sql.php"; try { $CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password); $CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } return $CONN; } public function LogIn() { if($_SERVER["REQUEST_METHOD"] === "POST") { $Username = $_POST["Username"]; $Password = $_POST["Password"]; $this->DB_Connect(); try { $SQL = "SELECT Password FROM Admins WHERE Username = :Username"; $SQL = $CONN->prepare($SQL); $SQL->execute(array('Username' => $Username)); $CountRows = $SQL->rowCount(); $Result = $SQL->fetch(PDO::FETCH_ASSOC); $PasswordCheck = $Result["Password"]; if($CountRows === "1" && password_verify($Password, $PasswordCheck)) { $_SESSION["LoginUser"] = $Username; $CONN = null; header("location: home.php"); exit(); } else { $Status = '<div class="alert alert-danger" role="alert">You have entered wrong data!</div>'; } } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } } $CONN = null; if(isset($Status)) { return $Status; } } 执行此操作但是当我运行代码时,我得到:

  

注意:未定义的变量:CONN in   第39行的C:\ XAMPP \ htdocs \ core \ Admin.class.php

     

致命错误:在null中调用成员函数prepare()   第39行的C:\ XAMPP \ htdocs \ core \ Admin.class.php

<!--//**********************************
    // Test Indeterminate Progress Bar
    //**********************************  -->
<script type="text/javascript">
    //Total out of range dialog
    $(function () {
        $("#progressbar").progressbar({
            value: false
        });
        $("button").on("click", function (event) {
            var target = $(event.target),
                progressbar = $("#progressbar"),
                progressbarValue = progressbar.find(".ui-progressbar-value");
                progressbar.progressbar("option", "value", false);
        });
    });

</script>  
<style>  
    #progressbar .ui-progressbar-value {    
        background-color: #ccc;  }  
</style>

1 个答案:

答案 0 :(得分:2)

$this->DB_Connect(); 返回一个值。它不会为您设置变量。您需要将变量设置为其返回值。

$CONN = $this->DB_Connect();