Is there anyway to make it so that the following code still uses a switch and returns b
not a
? Thanks!
$var = 0;
switch($var) {
This is not possible.
You can, however, put the if
statements inside the switch
:
switch($var) {
// Loose cases here
case 0:
if($var === NULL) {
return 'a';
}
// Fall through
default:
return 'b';
}
Or simply:
switch($var) {
// Loose cases here
default:
if($var === NULL) {
return 'a';
}
return 'b';
}
I just use
$var === null and $var = -1; // since switch is not type-safe
switch ( $var ) {
case 0:
# this tests for zero/empty string/false
break;
case -1:
# this tests for null
break;
}
I think this still looks very readable if the comment starting with //
is left behind (and the ones starting with #
are probably best deleted).
Create an assertion-like class and put whatever logic you want in it; so long as "true" methods return $this
(and nothing else to avoid false-positives.)
class Haystack
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
public function isExactly($n)
{
if ($n === $this->value)
return $this;
}
}
$var = new Haystack(null);
switch ($var) {
case $var->isExactly(''):
echo "the value is an empty string";
break;
case $var->isExactly(null):
echo "the value is null";
break;
}
Or you can put your switch inside the actual class:
class Checker
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
public function isExactly($n)
{
if ($n === $this->value)
return $this;
}
public function contains($n)
{
if (strpos($this->value, $n) !== false)
return $this;
}
public static function check($str)
{
$var = new self($str);
switch ($var) {
case $var->isExactly(''):
return "'$str' is an empty string";
case $var->isExactly(null):
return "the value is null";
case $var->contains('hello'):
return "'$str' contains hello";
default:
return "'$str' did not meet any of your requirements.";
}
}
}
var_dump(Checker::check('hello world')); # string(28) "'hello world' contains hello"
Of course that that point you might want to re-evaluate what you want to do with what you're checking and use a real validation library instead.
Here is your original code in a "strict" switch statement:
switch(true) {
case $var === null:
return 'a';
default:
return 'b';
}
This can also handle more complex switch statement like this:
switch(true) {
case $var === null:
return 'a';
case $var === 4:
case $var === 'foobar':
return 'b';
default:
return 'c';
}
One of the best way is to check NULL value by using is_null
<?php
echo getValue();
function getValue()
{
$var = 0;
switch(true) {
case is_null($var) : return 'a'; break;
default : return 'b'; break;
}
}
?>
make switch use === comparison not == comparison In PHP
Unfortunately switch uses loose comparison and as far as I know there's no way to change that.