0

我正在为我的应用程序完成我的登录功能,并且我收到trying to get property of non object了几行。第一个如下所示,它使用 user_data 对象内的对象属性 lock_date 对 is_user_locked 方法进行函数调用。我知道这意味着此时他们没有 user_data 可以使用,因此它不能使用这些属性。我很想知道我应该如何解释这一点,以免我滥用太多嵌套的 if 语句。

if (count($user_data) == 0) {
    $output = array('content' => 'The user was not found in the database!', 'title' =>
                'User Not Found');
}

if ($this->is_user_locked($user_data->lock_date)) {
     $output = array('content' => 'This user account is currently locked!', 'title' =>
                'Account Locked');
}

关于为什么会这样的任何想法?任何和所有建议都会有所帮助。

4

4 回答 4

1

我很想知道我应该如何解释这一点,以免我滥用太多嵌套的 if 语句。

这样的事情怎么样?

if( $user_data ) {
    // $user_data contains something so let's proceed
    if ($this->is_user_locked($user_data->lock_date)) {
        $output = array('content' => 'This user account is currently locked!', 'title' => 'Account Locked');
    }
} else {
    // Nothing in $user_data so throw Exception or display error
    $output = array('content' => 'The user was not found in the database!', 'title' =>
                'User Not Found');
}

请参阅此链接

if($var): same as $var == NULL.
于 2013-07-29T05:09:44.117 回答
1

我非常喜欢负 if 检查。这个想法是,如果你没有得到你所期望的,你会立即退出。这可以取回结果,或者进行真假检查。当然,您首先要使用 CI 表单验证来验证用户名。因此,例如在您的模型中,检查用户名的方法 - 如果结果为 0,则让它返回 false。然后在你的控制器中:

// Validate the user name and other form info 
// if validation passes, grab the username,  
// note the TRUE, that tells CI to run it through XSS clean  

 $username = $this->input->post( 'username', TRUE ) ;

 // if we did NOT get a user back from model, immediately go to new method
 if ( ! $user = $this->users_m->_findUser($username)  ) {
 $this->_userNotFound(); }

 // similar, if the user account is locked, go to new method
 // if you return an array from model this would be $user['lock_date'] 
 elseif ($this->isUserLocked($user->lock_date) == TRUE) {

 // DO NOT try and write messages etc here. put all that in a separate method 
 $this->_userAccountLocked(); }

 else {  
 // you have a $user and the user is not locked  
 // its tempting to write a bunch of stuff here
 // do not do that. keep it clean, and go to separate method 

 $this->_displayAccount($user) ; } 

请注意,我在所有方法名称之前都加了一个下划线——CI 会自动将它们设为私有。还要注意方法名称的 Camel 大小写 - 与下划线。有些人更喜欢它。

于 2013-07-30T04:45:23.923 回答
1

似乎正在发生的事情$user_data->lock_date应该是$user_data['lock_date']。我不能 100% 确定您发布的代码,但似乎您只是错误地引用了一个数组元素。

三元运算符可用于避免 if 语句

$user_data === null ? "it's null" : "otherwise it's not";
于 2013-07-28T23:37:11.237 回答
1

你可以这样做:

if (count($user_data) == 0) {
    $output = array('content' => 'The user was not found in the database!', 'title' =>
                'User Not Found');
} else if ($this->is_user_locked($user_data->lock_date)) {
     $output = array('content' => 'This user account is currently locked!', 'title' =>
                'Account Locked');
}

这与您的初始代码几乎相同,但有一个else抛出。

于 2013-07-30T04:59:45.083 回答