Created
May 21, 2018 03:31
-
-
Save zonuexe/46b9c0bbbdf5fdd4f04cfe62847f9aee to your computer and use it in GitHub Desktop.
compactっぽいユーザーランド実装
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function my_compact(...$var_names) | |
{ | |
$names = []; | |
foreach ($var_names as $n) { | |
if (is_string($n)) { | |
$names[] = $n; | |
} else { | |
$names = array_merge($names, $n); | |
} | |
} | |
return sprintf('$vars = []; | |
foreach (get_defined_vars() as $k => $v) { | |
if (in_array($k, %s)) { | |
$vars[$k] = $v; | |
} | |
} | |
return $vars;', var_export($names, true)); | |
} | |
function test_compact($piyo) | |
{ | |
$fuga = 'FUGA'; | |
return compact('hoge', 'fuga', 'piyo'); | |
} | |
function test_my_compact($piyo) | |
{ | |
$fuga = 'FUGA'; | |
return eval(my_compact('hoge', 'fuga', 'piyo')); | |
} | |
var_dump(test_compact('PIYO')); | |
var_dump(test_my_compact('PIYO')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ちなみにこの実装には、Hygienicではないマクロ(非衛生なマクロ)と同じ問題があります。
https://ja.wikipedia.org/wiki/%E5%81%A5%E5%85%A8%E3%81%AA%E3%83%9E%E3%82%AF%E3%83%AD