Combining bit flags into a PHP class constant

Possible duplicate:
Workaround for basic syntax that is not parsed

I am trying to allow developers to specify any combination of bits to indicate which pieces of data they want to include in the response.

class ClassName { const BUILD_DATE_RFC = 1; const BUILD_DATE_SQL = 2; const BUILD_DATE_SQLTIME = 4; const BUILD_DATE_UNIX = 8; // .... } 

This works in the sense that when I instantiate the class as follows:

 $whatever = new ClassName(BUILD_DATE_RFC|BUILD_DATE_SQL); 

This logic will be executed:

  if (self::BUILD_DATE_RFC & $this->metaBits) { $dateMeta['RFC'] = date('r'); } if (self::BUILD_DATE_SQL & $this->metaBits) { $dateMeta['SQL'] = date('Ym-d'); } if (self::BUILD_DATE_SQLTIME & $this->metaBits) { $dateMeta['SQL_time'] = date('Ymd H:i:s'); } 

All this works fine, except that I would like to define β€œshortcuts” something like BUILD_DATE_ALL, which would be the sum of all the bits associated with the DATE, so they would only need to specify that shortcut constant, not each separately.

I tried this, but it throws an error:

 const BUILD_DATE_ALL = (self::BUILD_DATE_RFC|self::BUILD_DATE_SQL|self::BUILD_DATE_SQLTIME|self::BUILD_DATE_UNIX); 

I also tried different approaches / syntaxes:

 const BUILD_REQUEST_ALL = self::BUILD_IP | self::BUILD_USERAGENT | self::BUILD_REFERER; 

and the other approach I tried:

 const BUILD_DEFAULT = self::BUILD_DATE_ALL|self::BUILD_REQUEST_ALL^self::BUILD_REFERER^self::BUILD_USERAGENT; 

The error I am getting is:

ErrorException: syntax error, unexpected '('

and the error I get for other approaches:

ErrorException: syntax error, unexpected '|', pending ',' or ';'

PHP doesn't seem to want to compute too much in the constant definition, and just wants to get one value, not a derived value. I assume that this is due to the fact that he does not want brackets and does not want | make further calculations. In addition, I tried to use '-' instead of | just to test my theory .. and yes, she complained that + is also unexpected.

How can I solve the problem, so I can define a β€œquick access bit”, which is the sum of the range of other constants already defined.

+6
source share
2 answers

You can calculate it yourself. Since these are bit flags, a pattern exists.

 class ClassName { const BUILD_DATE_RFC = 1; const BUILD_DATE_SQL = 2; const BUILD_DATE_SQLTIME = 4; const BUILD_DATE_UNIX = 8; const BUILD_DATE_ALL = 15; // 15 = 1|2|4|8; // .... } 
+6
source

Quote from the manual:

The value should be a constant expression, and not (for example) a variable, property, result of a mathematical operation, or a function call.

use | the operator is the result of the operation, therefore not pepited

+1
source

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


All Articles