Can I do something like this?
class Test
{
const FLAG1 = 'flag1.';
const FLAG2 = 'flag2.';
public function __construct() {}
public function myMethod($flags)
{
echo $flags
}
}
then use it like
$test = new Test();
$test->myMethod(Test::FLAG1|Test::FLAG2);
I tried to use this example but I get 2 as my echo.
I was just curious to see how I can use either CONST or DEFINE as parameters to a method.
I ask because I found this script that uses this technique and I found it curious
http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt
Yes, this is possible but not with the flag values you have now.
Bitwise operators work on… well, the bits. If I do
1001 OR 0110, I get1111. Therefore, if you want to be able to use constants like this, their values need to be powers of two.You can then test for the method by
AND-ing the parameter value of your function to a mask. For example, if someone passes inFLAG1|FLAG2, you can test for flag 2:0011 AND 0010 = 0010which is equal toFLAG2. In PHP, this would be($flags & FLAG2) == FLAG2to get a boolean of whether or not FLAG2 was passed inYou can see all of the bitwise operators here: http://php.net/manual/en/language.operators.bitwise.php
I should also point out that this would be generally considered poor form for PHP programming. Why do this when there are far better ways to pass in multiple parameters? Personally, I’d just accept an array.
Does this make sense? If not, ask more detailed questions and I will follow up.