0

I have been reading PHP conventions in OOP and come across the | operator/symbol which I cannot find any information on. After trial and error testing in an enviroment, I found that if the parameter is not a data-type int then the variable to the right of the parameter is outputted.

For example, let's use a class like this:

class MyClass {
    const FROM_DB = 1;
    const PUBLIC_ONLY = 0;

    public static function getSomething($input, $db = 0, $public = 1) {
        return $input;
    }
}

This use-case would return 1:

echo MyClass::getSomething( 'test' | MyClass::FROM_DB | MyClass::PUBLIC_ONLY );

This use-case would return 7:

echo MyClass::getSomething( 6 | MyClass::FROM_DB | MyClass::PUBLIC_ONLY );

Finally, this use-case would return 'test':

echo MyClass::getSomething( 'test' , MyClass::FROM_DB | MyClass::PUBLIC_ONLY );

I do not understand what the | is doing in this? I found it here. Can anyone explain what this is called and how it is used correctly?

Thank's in advance, see it working here.

Jaquarh
  • 5,698
  • 4
  • 19
  • 49
  • 1
    It is a `bitwise` operator, search on that. `1, 2, 4, 8, 16` etc set a bit in binary to 1 that you can compare against. `1|2` dont match, but `1|3` do as `2+1` make 3, meaning the bit in integer 3 is set in 1 as well. Very useful for flags – Xorifelse Nov 19 '16 at 01:28
  • Seem's confusing, I take it that it's used for mathematics? @Xorifelse – Jaquarh Nov 19 '16 at 01:33
  • Not at all, simply put you can save up to 32 booleans in 1 32 bit integer. This method saves a lot of storage in a database and allows for awesome 1 liners instead of nested if elses and its extremely fast. – Xorifelse Nov 19 '16 at 01:43
  • https://code.tutsplus.com/articles/understanding-bitwise-operators--active-11301 – Xorifelse Nov 19 '16 at 01:50

1 Answers1

1

It's a bitwise OR operator.

bitwise operations wikipedia

palako
  • 3,129
  • 2
  • 21
  • 32