CKTIS / PHP
Условия и разклонения
if преобразува условието в bool и 0 и „0“ пропускат верния клон. match сравнява строго стойност и тип и изчислява само избрания клон.
Версия: PHP 8.4; repository runtime, production runtime not attested
Синтаксис
if ($value) { /* branch */ }
match ($value) { 0 => "zero", default => "other" };if преобразува условието в bool и 0 и „0“ пропускат верния клон. match сравнява строго стойност и тип и изчислява само избрания клон. Без съвпадение или default води до UnhandledMatchError. Условията на клоновете се изчисляват поред до първото съвпадение. Изпълнява се само десният резултатен израз на избрания клон.
function classify($v){$branch="no"; if($v){$branch="yes";} return [$branch,match($v){0=>"int","0"=>"text",default=>"other"}];}
echo json_encode([classify(0),classify("0"),classify("00")]);
$trace=[]; $mark=function($tag,$v)use(&$trace){$trace[]=$tag;return $v;}; $r=match(2){$mark("c1",1)=>$mark("r1","A"),$mark("c2",2)=>$mark("r2","B"),$mark("c3",3)=>"C"};echo "\n",json_encode([$r,$trace]);
[["no","int"],["no","text"],["yes","other"]]
["B",["c1","c2","r2"]]
Примери
<?php
function classify($v){$branch="no"; if($v){$branch="yes";} return [$branch,match($v){0=>"int","0"=>"text",default=>"other"}];}
echo json_encode([classify(0),classify("0"),classify("00")]);
$trace=[]; $mark=function($tag,$v)use(&$trace){$trace[]=$tag;return $v;}; $r=match(2){$mark("c1",1)=>$mark("r1","A"),$mark("c2",2)=>$mark("r2","B"),$mark("c3",3)=>"C"};echo "\n",json_encode([$r,$trace]);
Резултат
[["no","int"],["no","text"],["yes","other"]] ["B",["c1","c2","r2"]]