Question:
What does "&" mean here in PHP?
Makes life more easier once we get used to it..(check example below carefully)
& usually checks bits that are set in both $a and $b are set.
have you even noticed how these calls works?
error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL);
So behind all above is game of bitwise operator and bits.
One usefull case of these is easy configurations like give below, so a single integer field can store thousands of combos for you.
Most people have already read the docs but didn't reliase the real world use case of these bitwise operators.
<?php
class Config {
// our constants must be 1,2,4,8,16,32,64 ....so on
const TYPE_CAT=1;
const TYPE_DOG=2;
const TYPE_LION=4;
const TYPE_RAT=8;
const TYPE_BIRD=16;
const TYPE_ALL=31;
private $config;
public function __construct($config){
$this->config=$config;
if($this->is(Config::TYPE_CAT)){
echo 'cat ';
}
if($this->is(Config::TYPE_DOG)){
echo 'dog ';
}
if($this->is(Config::TYPE_RAT)){
echo 'rat ';
}
if($this->is(Config::TYPE_LION)){
echo 'lion ';
}
if($this->is(Config::TYPE_BIRD)){
echo 'bird ';
}
echo "\n";
}
private function is($value){
return $this->config & $value;
}
}
new Config(Config::TYPE_ALL);
// cat dog rat lion bird
new Config(Config::TYPE_BIRD);
//bird
new Config(Config::TYPE_BIRD | Config::TYPE_DOG);
//dog bird
new Config(Config::TYPE_ALL & ~Config::TYPE_DOG & ~Config::TYPE_CAT);
//rat lion bird