


Detailed explanation of examples of PHP bit operator permission operations
Regarding the bit operations of binary numbers, the three most common operations are "OR, AND, NOT". Of course, PHP Manual also has "XOR, These three operations are "left shift and right shift".
How to define permissions
Define the value of permissions according to 2 to the Nth power, and so on. Why define it this way? This definition ensures that there is only one 1 in each permission value (binary), and it corresponds to exactly one permission. For example:
define('ADD', 1); // 增加权限 define('UPD', 2); // 修改权限 define('SEL', 4); // 查找权限 define('DEL', 8); // 删除权限
Permission operation
Permission operation actually involves the concept of "role". Performing permission operations is nothing more than granting certain permissions to a certain role, prohibiting certain permissions, and detecting whether a certain role has certain permissions. Relative to these three operations. It can be easily implemented using arithmetic operations between binary numbers.
// 给予某种权限用到“位或”运算符 $a_access = ADD | UPD | SEL | DEL; // a拥有增删改查权限 $b_access = ADD | UPD | SEL; // b拥有增改查权限 $c_access = ADD | UPD; // c拥有增改权限 // 禁止某种权限用“位与”和“位非”运算符 $d_access = $c_access & ~UPD; // d只拥有了增权限 // 检测是否拥有某种权限用到“位与”运算符 var_dump($b_access & ADD); // 1代表b拥有增权限 var_dump($b_access & DEL); // 0代表b不拥有删权限
Implementing simple permission classes and role classes
Using the above permission operation method, it can be simply encapsulated into a permission class and a role class.
<?php /** * 简单权限类 */ class Peak_Auth { /** * 权限类计数器 * 作用在于生成权限值 * * @var int */ protected static $authCount = 0; /** * 权限名称 * * @var string */ protected $authName; /** * 权限详细信息 * * @var string */ protected $authMessage; /** * 权限值 * * @var int 2的N次方 */ protected $authValue; /** * 构造函数 * 初始化权限名称、权限详细信息以及权限值 * * @param string $authName 权限名称 * @param string $authMessage 权限详细信息 */ public function construct($authName, $authMessage = '') { $this->authName = $authName; $this->authMessage = $authMessage; $this->authValue = 1 << self::$authCount; self::$authCount++; } /** * 本类不允许对象复制操作 */ private function clone() { } /** * 设置权限详细信息 * * @param string $authMessage */ public function setAuthMessage($authMessage) { $this->authMessage = $authMessage; } /** * 获取权限名称 * * @return string */ public function getAuthName() { return $this->authName; } /** * 获取权限值 * * @return int */ public function getAuthValue() { return $this->authValue; } /** * 获取权限详细信息 * * @return string */ public function getAuthMessage() { return $this->authMessage; } } /** * 简单角色类 * * @author 27_Man */ class Peak_Role { /** * 角色名 * * @var string */ protected $roleName; /** * 角色拥有的权限值 * * @var int */ protected $authValue; /** * 父角色对象 * * @var Peak_Role */ protected $parentRole; /** * 构造函数 * * @param string $roleName 角色名 * @param Peak_Role $parentRole 父角色对象 */ public function construct($roleName, Peak_Role $parentRole = null) { $this->roleName = $roleName; $this->authValue = 0; if ($parentRole) { $this->parentRole = $parentRole; $this->authValue = $parentRole->getAuthValue(); } } /** * 获取父角色的权限 */ protected function fetchParenAuthValue() { if ($this->parentRole) { $this->authValue |= $this->parentRole->getAuthValue(); } } /** * 给予某种权限 * * @param Peak_Auth $auth * @return Peak_Role 以便链式操作 */ public function allow(Peak_Auth $auth) { $this->fetchParenAuthValue(); $this->authValue |= $auth->getAuthValue(); return $this; } /** * 阻止某种权限 * * @param Peak_Auth $auth * @return Peak_Role 以便链式操作 */ public function deny(Peak_Auth $auth) { $this->fetchParenAuthValue(); $this->authValue &= ~$auth->getAuthValue(); return $this; } /** * 检测是否拥有某种权限 * * @param Peak_Auth $auth * @return boolean */ public function checkAuth(Peak_Auth $auth) { return $this->authValue & $auth->getAuthValue(); } /** * 获取角色的权限值 * * @return int */ public function getAuthValue() { return $this->authValue; } } ?>
The above is the detailed content of Detailed explanation of examples of PHP bit operator permission operations. For more information, please follow other related articles on the PHP Chinese website!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingclassesfromtheirdependencies.1)UseConstructorInjectiontopassdependenciesviaconstructors,ensuringfullinitialization.2)EmploySetterInjectionforpost-creationdependencychanges,t

Pimple is recommended for simple projects, Symfony's DependencyInjection is recommended for complex projects. 1)Pimple is suitable for small projects because of its simplicity and flexibility. 2) Symfony's DependencyInjection is suitable for large projects because of its powerful capabilities. When choosing, project size, performance requirements and learning curve need to be taken into account.

DependencyInjection(DI)inPHPisadesignpatternwhereclassdependenciesarepassedtoitratherthancreatedinternally,enhancingcodemodularityandtestability.Itimprovessoftwarequalityby:1)Enhancingtestabilitythrougheasydependencymocking,2)Increasingflexibilitybya


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
