Friday, May 27, 2011

Keyword Functions in PHP

So, as spurned by a comment on hacker news relating to the lack of ability for keyword arguments in php I figured I would expound more upon the Phutility library, in particular the Func module.

Check it out:

#say you have a function (perhaps defined by you, perhaps not)

namespace SomeNamespace;
use Phutility\Func;

function testFunc($name, $eyes, $hair = 'blonde', $age = 0, $weight = 200, $goatFace = 'definitely') {
return array(
'name' => $name,
'eyes' => $eyes,
'hair' => $hair,
'age' => $age,
'weight' => $weight,
'goatFace' => $goatFace);
}

#if you want a keyword wrapper for it:

$testFuncWrapper = Func::keyword('\SomeNamespace\testFunc');

$result = $testFuncWrapper(
age, 30,
name, 'peter'
);

/*would yield a $result of
array(
'name' => 'peter',
'eyes' => 'blue',
'hair' => 'blonde',
'age' => 30,
'weight' => 1200,
'goatFace' => 'definitely'
)
*/

# If you want to not have a variable func you would need to do something like:
function TestFuncWrapper() {
static $wrapper;
if(!$wrapper) {
$wrapper = Func::keyword('\SomeNamespace\TestFunc');
}

return call_user_func_array($wrapper, func_get_args());
}

#a little gnarlier but this is the price we pay to call it like:

$result = TestFuncWrapper(
goatFace, 'NoWay'
);

#oops this would yield an exception because name and age are required!


If this is at all interesting to you and you'd like to use it or contribute, the source and tests are all up on github.

1 comment:

angel26 said...

That looks really stuffed with the important keywords and functions of PHP.Thanks for sharing these here.Helpful !
web design company