用戶狀態保存是一個很常見的需求,一般用來保存用戶狀態的方式是在數據庫表中創建多個字段來存儲相應的用戶狀態,比如要保存用戶是否綁定了手機號和QQ,則需要2個字段(mobile,qq)來保存。
?php
/**
* 使用二進制來保存用戶狀態
*/
//首先定義4個用戶狀態
define('MOBILE', 1); //手機號綁定
define('EMAIL', 2); //郵箱綁定
define('WECHAT', 4); //微信綁定
define('QQ', 8); //QQ綁定
//模擬用戶類
class User {
public $user_name = "";
public $status = 0; //用來保存用戶狀態
function __construct($user_name, $status) {
$this->user_name = $user_name;
$this->status = $status;
}
}
//new一個測試用戶
$test_user = new User("test_user", 0);
//先判斷用戶是否綁定了手機號
if (($test_user->status MOBILE) == MOBILE)
echo "first:該用戶已經綁定手機號,用戶狀態是:" . $test_user->status . "/br>";
else
echo "first:該用戶沒有綁定手機號,用戶狀態是:" . $test_user->status . "/br>";
//接著該用戶去綁定了手機號 微信 和 QQ
$test_user->status = MOBILE | WECHAT | QQ;
//再判斷一下用戶是否綁定了手機號
if (($test_user->status MOBILE) == MOBILE)
echo "second:該用戶已經綁定手機號,用戶狀態是:" . $test_user->status . "/br>";
else
echo "second:該用戶沒有綁定手機號,用戶狀態是:" . $test_user->status . "/br>";
//再判斷一下用戶有沒有綁定郵箱
if (($test_user->status EMAIL) == EMAIL)
echo "third:該用戶已經綁定郵箱,用戶狀態是:" . $test_user->status . "/br>";
else
echo "third:該用戶沒有綁定郵箱,用戶狀態是:" . $test_user->status . "/br>";
//然后這個用戶解除了手機號綁定
$test_user->status = ($test_user->status (~MOBILE));
//再次判斷用戶是否綁定了手機號
if (($test_user->status MOBILE) == MOBILE)
echo "fourth:該用戶已經綁定手機號,用戶狀態是:" . $test_user->status . "/br>";
else
echo "fourth:該用戶沒有綁定手機號,用戶狀態是:" . $test_user->status . "/br>";