在PHP中从对象中提取字符串

时间:2014-04-18 21:06:17

标签: php arrays object

我确信这非常明显,但我是PHP的初学者。我只是试图从对象中提取一些数据,将数据存储在一个数组中并将该数组分配给$_SESSION[]。数据是用户名和用户ID。

但目前无效。

其余代码工作正常。 $user->id;$user->user;中有值。我似乎无法将它们粘贴到$s_id$s_user

User.php也正常工作我只是将其包含在内作为参考。

的login.php:

<?php // login.php
require_once("user.php");
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors','On');
session_start();

$_SESSION['userid'] = ''; // Force a logout
$r_userid = $_REQUEST['userid'];
$r_passwd = $_REQUEST['passwd'];
$result = array();
$result['success'] = false;
if (isset($r_userid) && ($r_userid != '') && isset($r_passwd) && ($r_passwd != '')) {
    $user = User::findOnIdPassword($r_userid, $r_passwd);
    if ($user) {
        $s_id = $user->id; 
        $s_user = $user->user;
        $_SESSION['userid'] = array($s_id, $s_user);
        $result['message'] = "Successful Login";
        $result['success'] = true;
    } else {
        $result['message'] = "Login Failed, please try again";
    }
} else {
    $result['message'] = "Missing User id and password";
}
print(json_encode($result));
?>

user.php:

<?php // user.php
require_once "sql.php";

Class User {
private $id;
private $user;
private $email;
private $password;

public function __construct($id, $user, $password, $email) {
    $this->id = $id;
    $this->user = $user;
    $this->password = $password;
    $this->email = $email;
}

public function insert() {
    $query = "insert into Users (username, password, email) values"
             . "('$this->user', '$this->password', '$this->email');";
    $result = Sql::query($query);
    return $result;
}

public function getId() {
    return $this->id;
}

public function getEmail() {
    return $this->email;
}

public static function findOnIdPassword($user, $passwd) {
    $query = "select * from Users where username = '$user' and password = '$passwd';";
    if ($result = Sql::query($query)) {
        if (mysqli_num_rows($result) != 1) {
            $result = null;
        } else {
            $row = mysqli_fetch_assoc($result);
            $id = $row['id'];
            $user = $row['username'];
            $password = $row['password'];
            $email = $row['email'];
            $result = new User($id, $user, $password, $email);
        }
    }
    return $result;
}

// findOnEmail(email)
// update(newEmail, newPassword)
// findAll for admin
}

?>

谢谢!

2 个答案:

答案 0 :(得分:1)

问题是您正在尝试访问私有类之外的属性。这里:

$s_id = $user->id; 
$s_user = $user->user;

您应该使用getId()并创建另一个方法来获取用户名:

$s_id = $user->getId();
$s_user = $user->getUser();

答案 1 :(得分:1)

您要访问的属性是私有的。但对于$ id,您可以使用一种方法来提取数据:

$s_id = $user->getId();

对于用户,您可以在用户类内的user.php中创建一个额外的get方法:

public function getUser(){
    return $this->user;
}

然后在login.php中使用它:

$s_user = $user->getUser();

但至于你的代码,我看不出通过User对象提取用户名的原因。我看到$ r_userid用作User :: findOnIdPassword($ user,$ passwd)方法的$ user参数的实际值,它在SQL“WHERE username ='$ user'”子句中应用。并且$ user再次从数据库中提取为用户名字段。因此,如果SQL查询成功,则$ r_userid和$ s_user都将具有相同的值。