使用二进制保存用户状态

栏目: PHP · 发布时间: 8年前

内容简介:使用二进制保存用户状态

前言

用户状态保存是一个很常见的需求,一般用来保存用户状态的方式是在数据库表中创建多个字段来存储相应的用户状态,比如要保存用户是否绑定了手机号和QQ,则需要2个字段(mobile,qq)来保存。

如果使用二进制来保存用户的状态的话则只需要1个字段(status)就能保存多个用户状态。

当然使用二进制来保存也有一些坏处,比如不能存储详细的信息,只能用来判断状态,而且在数据库中可读性也比较差。下面是一个比较简单的Demo。

代码

<?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>";

以上所述就是小编给大家介绍的《使用二进制保存用户状态》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

We Are the Nerds

We Are the Nerds

Christine Lagorio-Chafkin / Hachette Books / 2018-10-2 / USD 18.30

Reddit hails itself as "the front page of the Internet." It's the third most-visited website in the United States--and yet, millions of Americans have no idea what it is. We Are the Nerds is an eng......一起来看看 《We Are the Nerds》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具