Created
March 30, 2015 15:23
-
-
Save krmgns/fe7e3161980cd2370b6f to your computer and use it in GitHub Desktop.
Argument extracting with PHP (shorcut).
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 arguments($limit = null) { | |
$callee =@ debug_backtrace(null, 2)[1]; | |
if (empty($callee)) { | |
throw new \Exception(sprintf( | |
'Could not find callee in %s() funtion!', __function__)); | |
} | |
$return = []; | |
// int args (for list) | |
// arguments() -> fill all | |
// arguments(2) -> fill 2 only | |
if ($limit === null || is_int($limit)) { | |
$limit = ($limit !== null) ? $limit : count($callee['args']); | |
for ($i = 0; $i < $limit; $i++) { | |
$return[$i] = array_key_exists($i, $callee['args']) | |
? $callee['args'][$i] : null; | |
} | |
} | |
// str args (for extract / assoc array) | |
// arguments('x','z') | |
else { | |
foreach (func_get_args() as $i => $name) { | |
$return[$name] = array_key_exists($i, $callee['args']) | |
? $callee['args'][$i] : null; | |
} | |
} | |
return $return; | |
} | |
function foo() { | |
$args = arguments('x', 'y'); | |
var_dump($args['x']); | |
var_dump($args['y']); | |
// extract(arguments('x', 'y')); | |
// var_dump($x); | |
// var_dump($y); | |
// list($x, $y, $z) = arguments(); | |
// var_dump($x); | |
// var_dump($y); | |
// var_dump($z); | |
// list($x, $y, $z) = arguments(2); // err! | |
// var_dump($x); | |
// var_dump($y); | |
// var_dump($z); // err! | |
} | |
function foo2() { | |
foo('kerem', '..', '...'); | |
// foo(null); | |
} | |
// foo2(); | |
foo('kerem', '..', '...'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment