php8 新特性 match

 https://www.php.net/manual/en/control-structures.match.php

 

 

 

      $shape = ['type' => 'circle', 'radius' => '10'];

$res = match ($shape) {
['type' => 'circle', 'radius' => 10] => 'Circle with radius ' . $shape['radius'],
['type' => 'circle', 'radius' => '10'] => 'Circle with radius10 ' . $shape['radius'],
['type' => 'circle', 'radius' => 12] => 'Circle with radius ' . $shape['radius'],
default => 'Unknown shape',
};

dd($res); 

强类型匹配: 这里的10 是字符串 会匹配到第二个选项


左边可以有多个值,用,隔开 相当于 逻辑 or
$result = match ($x) {
// This match arm:
$a, $b, $c => 5,
// Is equivalent to these three match arms:
$a => 5,
$b => 5,
$c => 5,
};


和switch 一样 支持 default


$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};


public static function getCount(){
return 113;
}

//来源判断
public function checkoutFrom($str)
{

$shape = 113;

$res = match($shape){
self::getCount() => self::getCount(),
'demo' => ' 3.',
default => 'Unknown shape',
};
dd($res);
}

// 113



比较
    //来源判断
public function checkoutFrom($str)
{

return match ($str) {
strpos($str, 'contact@digipart.com') !== false => 'digipart',
strpos($str,'messagesend@netcomponents.com') !== false => 'netcomponents',
(strpos($str,'info') !== false && strpos($str,'hkinventory.com') !== false || strpos($str,'alert@hki') !== false) => 'hkinventory',
strpos($str,'autosend@autosend.icsource.com') !== false => 'icsource',
strpos($str,'noreply@octopart.com') !== false => 'octopart',
strpos($str,'robot@efind.ru') !== false => 'efind ',
default => 'false',
};


// switch ($str) {
// case strpos($str, 'contact@digipart.com') !== false:
// return 'digipart';
// case strpos($str,'messagesend@netcomponents.com') !== false:
// return 'netcomponents';
// case (strpos($str,'info') !== false && strpos($str,'hkinventory.com') !== false || strpos($str,'alert@hki') !== false):
// return 'hkinventory';
// case strpos($str,'autosend@autosend.icsource.com') !== false:
// return 'icsource';
// case strpos($str,'noreply@octopart.com') !== false:
// return 'octopart';
// case strpos($str,'robot@efind.ru') !== false:
// return 'efind';
// default:
// return false;
// }

if(strpos($str, 'contact@digipart.com') !== false){
return 'digipart';
} else if(strpos($str,'messagesend@netcomponents.com') !== false){
return 'netcomponents';
}else if(strpos($str,'info') !== false && strpos($str,'hkinventory.com') !== false || strpos($str,'alert@hki') !== false){
return 'hkinventory';
}else if(strpos($str,'autosend@autosend.icsource.com') !== false){
return 'icsource';
}else if(strpos($str,'noreply@octopart.com') !== false){
return 'octopart';
}else if(strpos($str,'robot@efind.ru') !== false){
return 'efind';
}
return false;
}







posted @ 2024-04-13 17:04  列王纪  阅读(138)  评论(0)    收藏  举报