PHP:如何正确使用return语句

时间:2012-01-17 04:48:07

标签: php

问题:我有一个名为'user'的类和一个名为'registerUser'的函数。我想成功注册一个页面,但注册到另一个页面不成功。

我还没有填写退货声明,因为我不确定这是否是我能解决问题的方法。我是php的新手,并相信这可行,但正如我所说,我是新人,仍在学习。

class User {
    function registerUser($userName, $userPassword) {
    // Connect to database
    $dbLink = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
    if(!$dbLink) die("Could not connect to database. " . mysql_error());

    // Select database
    mysql_select_db($this->dbName);

    // Insert data
    $query = "insert into $this->dbUserTable values (NULL, \"$userName\", \"$userPassword\")";
    $result = mysql_query($query);

    // Test to make sure query worked
    if(!$result) {
        return(false);
    }

    // Get the user ID
    $this->userID = mysql_insert_id();

    // Close database connection
    mysql_close($dbLink);

    // Assign the values to the data members
    $this->userName = $userName;
    $this->userPassword = $userPassword;
    return(true);
} // End registerUser()
}

我调用此类的PHP代码很简单。

    <?
// processRegister.php
//////////////////////

// First include the class definition
include('UserClass.php');

// Next, create an instance of the class
$newUser = new User;

// Call the registerUser() method, passing in the required variables
if ($newUser->registerUser($userName, $userPassword)) {
  header('Location: www.google.com');
} 
else {
  header('Location: www.yahoo.com.com');
}
?>

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

我会这样做:

if ($newUser->registerUser($userName, $userPassword)) {
  $newUser->displayUserInfo();
} else {
  echo "Errors, ahoy!"
}

删除die()语句,只需添加return false(或将die替换为echo,如果需要调试消息,请添加return false

非常结束时,添加return true

答案 1 :(得分:0)

我认为您应该使用PHP函数mysql_insert_id()返回最后插入的用户ID。基于此,您可以识别注册过程是否成功。

class User {
function registerUser($userName, $userPassword) {
        // Connect to database
        $dbLink = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
        if(!$dbLink) die("Could not connect to database. " . mysql_error());

        // Select database
        mysql_select_db($this->dbName);

        // Insert data
        // Notice the "$userName" and "$userPassword" - these are the ones
        // passed in from your main script, not the class/object variables!
        $query = "insert into $this->dbUserTable values (NULL, \"$userName\", \"$userPassword\")";
        $result = mysql_query($query);

        return mysql_insert_id();

}

processRegister.php

<?
// processRegister.php
//////////////////////

// First include the class definition
include('UserClass.php');

// Next, create an instance of the class
$newUser = new User;

// Call the registerUser() method, passing in the required variables
$user_id = $newUser->registerUser($userName, $userPassword);

if(intval($user_id) && $user_id>0){
    //redirect to success page
}else{
    //redirect to error page
}

?>