2017-06-11 23 views
0

所以這裏的代碼:關鍵定義,值集,但仍然被定義爲空

// Check to see if user has admin permissions 
if($user->hasPermission('admin')) { 
    // Display Admin Backpage Link 
    echo "<li><a href='" . Config::get('links/app_root') . "admin/'>Admin</a></li>"; 
} 

很明顯,當我打電話hasPermission()方法,我指定,我要檢查,如果用戶有權限管理員。

這裏是我的hasPermission方法:

// User Has Permission Check 
public function hasPermission($key) { 
    // Pull from the groups table, where the id (group) equals the assigned group of the user 
    // id: 1 for standard users (No permissions/Json stored) 
    // id: 2 for Moderators (Json: {"moderator":1} 
    // id: 3 for admins (Json: {"admin":1,"moderator":1} 
    $groups = $this->_db->get('groups', array('id', '=', $this->data()->groups)); 

    // Check if user is in a group or not 
    if($groups->count()) { 
     $permissions = json_decode($groups->first()->permissions, true); 
     if($permissions[$key] == true) { 
      return true; 
     } 
    } 

    // user does not have permission 
    return false; 
} 

我稱之爲後,我得到這個錯誤:

Notice: Undefined index: admin in /Applications/XAMPP/xamppfiles/htdocs/OOP Login System/core/classes/User.php on line 127

127行是這一行:

if($permissions[$key] == true) { 

我米不理解爲什麼管理員爲空。用於管理我的數據庫權限被設置爲我的MySQL數據庫中的以下內容:

{ 
    "admin": 1, 
    "moderator": 1 
} 

請告訴我真的是瘋了,這是所有工作得很好,我也沒有編輯的用戶類,因爲我做到了在所有。現在我有「主持人」權限以及與JSON設置爲:

{ 
    "moderator": 1 
} 

,每當我打電話hasPermission('moderator')我沒有得到這個錯誤。就像我以前說過的,我不明白哪裏出了問題。

+0

考慮使用'如果(!空($權限[$關鍵]))'代替,因爲這將處理根本沒有設置的權限。 –

+0

看起來像那樣工作,哇,我覺得自己像一個白癡。但是,我仍然不明白爲什麼它首先打破了。 :/嚴重... –

+0

'$ this-> data() - > groups'的值是多少?你似乎認爲它是3,但檢查一下會很好。或者,如果它可以是1或2,請確保不要假設存在「管理員」密鑰。 – trincot

回答

0

交換線路127從

if($permissions[$key] == true) { 

到:

if(!empty($permissions[$key])) { 
0

爲了幫助減少錯誤,以及可能正在嘗試catch塊封裝好的做法。

try { 
    $error = 'Always throw this error'; 
    throw new Exception($error); 

    // Code following an exception is not executed. 
    echo 'Never executed'; 

} catch (Exception $e) { 
    echo 'Caught exception: ', $e->getMessage(), "\n"; 
} 

,並考慮按照使用評論,如果(!空($權限[$關鍵]))

相關問題