📜 ⬆️ ⬇️

Passing function arguments by name in PHP

When refactoring code, there was one small idea about calling methods. Sometimes there is a need to pass an argument to a function by name. For example, when it is impossible (or inconvenient) to transfer the list in the right order. Such cases can be calls of dynamic blocks from template engines: in the template we have {{mymodule action = foo second = 124322 fourth = 'catalog' first = 'name' third = 'foo'}} and the code has the following function synatura - function foo ($ first, $ second, $ third, $ fourth) . a similar approach is used in the Magento system to call blocks from ley-outs; or it is necessary to transfer data to the method based on a filter in some associative array. In PHP4, the possible solution was to put the entire list of arguments in the array. In PHP version 5, there is the Reflection API , with which it is possible to do this. Perl, Python (, ...) can, so why should it be impossible in PHP? :)

UPD : the pastebin code is overwritten, here is the helper method for this (call like $ object -> __ named ('methodNameHere', array ('arg3' => 'three', 'arg1' => 'one')) )
/**
* Pass method arguments by name
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __named($method, array $args = array())
{
$reflection = new ReflectionMethod($ this , $method);

$pass = array();
foreach ($reflection->getParameters() as $param)
{
/* @var $param ReflectionParameter */
if (isset($args[$param->getName()]))
{
$pass[] = $args[$param->getName()];
}
else
{
$pass[] = $param->getDefaultValue();
}
}

return $reflection->invokeArgs($ this , $pass);
}


* This source code was highlighted with Source Code Highlighter .

')

Source: https://habr.com/ru/post/95335/


All Articles