Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created July 9, 2022 04:58
Show Gist options
  • Save nexpr/a29b18618df6289f705517387b546b65 to your computer and use it in GitHub Desktop.
Save nexpr/a29b18618df6289f705517387b546b65 to your computer and use it in GitHub Desktop.
PHPのアロー関数で代入やif分岐できない制限を回避
<?php
$let = fn(...$a) => array_pop($a)(...$a);
$v1 = 10;
$let($v1 + 1, fn($v2) =>
$let($v2 + 1, fn($v3) =>
$let($v3 + 1, fn($v4) =>
var_dump($v1, $v2, $v3, $v4)
)));
/*
int(10)
int(11)
int(12)
int(13)
*/
$null = fn() => null;
$if = fn($c, $t, $f=null) => $c ? $t() : ($f ?? $null)();
$x = 1;
$y = -1;
var_dump(
$if($x === 0,
fn() => 1,
fn() => 2,
)
);
var_dump(
$if($x < 0,
fn() => $if($y < 0,
fn() => 1,
fn() => 2,
),
fn() => $if($y < 0,
fn() => 3,
fn() => 4,
)
)
);
var_dump(
$if($x === 1,
fn() => 1,
$if($x === 2,
fn() => 2,
$if($x === 3,
fn() => 3,
)))
);
/*
int(2)
int(3)
int(1)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment