我有两个这样的代码:
class User()
{
var $permission = array();
function __construct()
{
$Permission_Class = new Permission();
// What to do here with $this->permission
// to linked with $Permission_Class->check_permission()
// for getting user's permission?
}
}
class Permission()
{
var $permission_list = array(
'can_read' => 'yes',
'can_write' => 'no'
);
public function check_permission($permission_name)
{
return $this->permission_list[$permission_name];
}
}
我想通过简单地将权限名称作为数组输入来获得用户的权限,尤其是通过以下方式:
$User1 = new User();
$read_permission = $User1->permission['can_read']; // not working currently
或者更好的是这样:
$permission = $User1->permission();
var_dump($permission['can_read']); // expected 'yes'
因此预期结果是类中的'can_read'权限具有'是'值。 我能做些什么才能实现这一目标?
谢谢。
答案 0 :(得分:0)
简单,只需将其包起来!
class User()
{
private $permission = array();
function __construct()
{
$this->permission = new Permission();
}
public function permission($key)
{
return $this->permission->check_permission($key);
}
}
$user->permission('can_read');
请务必检查$key
是否为现有密钥。 E.G:
/**
* $default would contain the value you want your
* requested permission to have if it does not exist
*/
public function check_permission($permission_name, $default = NULL)
{
return isset($this->permission_list[$permission_name])
? $this->permission_list[$permission_name]
: $default;
}
// We want can write to be `FALSE` unless otherwise specified
$user->permission('can_write', FALSE);
评论后更新
事件虽然我建议不要使用全局权限数组(例如,如果你想知道其他用户是否具有can_write权限,你可以轻松地重写其中一些):
/** class User **/
public function permission($key = NULL)
{
// If no key specified, return entire array
if($key === NULL)
{
return $this->permission->permission_list;
}
return $this->permission->check_permission($key);
}
然后在你的应用程序的某个地方
global $permissions;
$permissions = $user->permission();