⬆️ ⬇️

Bit operations in PHP with examples

Inspired by the article about handling critical errors in PHP . I noticed that despite the fact that the error codes in PHP are specially sharpened for bit operations, however, in the examples of the article that are in the comments, regular comparison operators are used to check the error codes.



For example, there were such options:

if ($error['type'] == E_ERROR || $error['type'] == E_PARSE || $error['type'] == E_COMPILE_ERROR){…}


if(in_array($error['type'], array(E_ERROR, E_PARSE,  E_COMPILE_ERROR)) {…}


.





() . , , ().

5 , 00000101.



6 :



$a & $b — ( , $a $b)

$a | $b — ( , $a $b)

$a ^ $b — ( $a $b, )

~$a — (, 1 0, )

$a << $b — ( $a $b)

$a >> $b — ( $a $b)





, .

: , , , . 4 , 4- , 1 — , , 0 — . .







:



define('U_READ', 1 << 0);   // 0001
define('U_CREATE', 1 << 1); // 0010
define('U_EDIT', 1 << 2);   // 0100
define('U_DELETE', 1 << 3); // 1000
define('U_ALL', U_READ | U_CREATE | U_EDIT | U_DELETE); // 1111




.

$user_perm =  U_READ; //   


.

$user_perm =  U_READ | U_DELETE; //    


.

$user_perm =  U_ALL; //  


, .

$user_perm =  U_ALL ^ U_DELETE;  //     
$user_perm =  U_ALL & ~ U_DELETE; //     ,    2 


, , 1, 0, . 0, .





, , .. . .

if($user_perm & U_READ) //    ?


,

if($user_perm & ( U_READ | U_DELETE )) //     / 




- ,

$user_perm &= ~ U_DELETE; //  




. , :

if($error['type'] & ( E_ERROR | E_PARSE | E_COMPILE_ERROR )) {…}




P.S.: , , PHP.

:

Wikipedia

PHP


')

Source: https://habr.com/ru/post/134557/



All Articles