我该什么时候回来?

时间:2016-11-19 16:43:19

标签: php oop

我正在努力为存储在数据库中的部分创建一个访问对象。这是一个过程的skellington,它包含静态数据,直到我能够使原理工作。

Integer

此类最终将自动从数据库加载数据,但目前该类具有默认值。

Double

这就是搞砸的地方,我可以说如果第一次失败就无法满足第二和第三个条件,我怎么能阻止这个?

class User {
    const IS_ADMIN = 1;
    const IS_MODERATOR = 2;
    const IS_MEMBER = 4;
}

当priverlidge的默认值为1时,该示例用法正常工作:

class Scope {
    private $priv = [];

    public function __construct() {
        $this->priv = [1];
    }

    public function getPrivilidges() {
        return $this->priv;
    }
}

当priverlidge的默认值为2时,其用法很正常:

class Priverlidges {
    public function canView($type, Scope $scope) {
        if($type & User::IS_ADMIN) {
            foreach($scope->getPrivilidges() as $p) {
                if($p == User::IS_ADMIN) continue;
                return false;
            }
            return true;
        }

        if($type & User::IS_MODERATOR) {
            foreach($scope->getPrivilidges() as $p) {
                if($p == User::IS_MODERATOR) continue;
                return false;
            }
            return true;
        }

        if($type & User::IS_MEMBER) {
            foreach($scope->getPrivilidges() as $p) {
                if($p == User::IS_MEMBER) continue;
                return false;
            }
            return true;
        }
    }
}

任何人都可以帮我回复真假吗?提前致谢。
P.S - 用户可以是Mods和Admins

编辑:我曾尝试使用echo (int)(new Priverlidges)->canView(User::IS_ADMIN, new Scope()); 但仍不确定何时返回值echo (int)(new Priverlidges)->canView(User::IS_MODERATOR | User::IS_ADMIN, new Scope()); // it returns false at the first condition in_array(),因为如果第二种方法运行,它会被覆盖。

1 个答案:

答案 0 :(得分:0)

我明白了。首先,使用占位符($this->_state)检查用户是否尚未通过身份验证。然后检查用户类型并检查它是否在范围内。

class Priverlidges {

    private $_state = false;

    public function canView($type, Scope $scope) {
        if(!$this->_state && $type & User::IS_ADMIN && in_array(User::IS_ADMIN, $scope->getPrivilidges())) {
            $this->_state = true;
        }

        if(!$this->_state && $type & User::IS_MODERATOR && in_array(User::IS_MODERATOR, $scope->getPrivilidges())) {
            $this->_state = true;
        }

        if(!$this->_state && $type & User::IS_MEMBER && in_array($scope->getPrivilidges(), User::IS_MEMBER)) {
            $this->_state = true;
        }

        return $this->_state;
    }

}