Home > php教程 > php手册 > 使用命名参数调用 PHP 函数

使用命名参数调用 PHP 函数

WBOY
Release: 2016-06-21 08:51:30
Original
998 people have browsed it

  Python 很棒的一点是它能够使用名字将参数传递到一个函数,看起来是这样的:

  my_foo_function(param_name="value", another_param_name="another value")

  今天我想在 PHP 5.4 中做同样的事情(可轻松移植到 PHP 5.3),我写了一个 call_user_func_named 函数,类似 PHP 内置的 call_user_func_array 函数,代码如下:

$x = function($bar, $foo="9") {
  echo $foo, $bar, "\n";
};

class MissingArgumentException extends Exception {
}

function call_user_func_named_array($method, $arr){
  $ref = new ReflectionFunction($method);
  $params = [];
  foreach( $ref->getParameters() as $p ){
    if( $p->isOptional() ){
      if( isset($arr[$p->name]) ){
        $params[] = $arr[$p->name];
      }else{
        $params[] = $p->getDefaultValue();
      }
    }else if( isset($arr[$p->name]) ){
      $params[] = $arr[$p->name];
    }else{
      throw new MissingArgumentException("Missing parameter $p->name");
    }
  }
  return $ref->invokeArgs( $params );
}

call_user_func_named_array($x, ['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss
call_user_func_named_array($x, ['bar' => 'world']); //Only pass one parameter
call_user_func_named_array($x, []); //Will throw exception

 

  更新:很感谢一些热心的贡献者做的一些改进:

 

 

$x = function($bar, $foo="9") {
  echo $foo, $bar, "\n";
};

class MissingArgumentException extends Exception {
}

function call_user_func_named_array($method, $arr){
  $ref = new ReflectionFunction($method);
  $params = [];
  foreach( $ref->getParameters() as $p ){
    if (!$p->isOptional() and !isset($arr[$p->name])) throw new MissingArgumentException("Missing parameter $p->name");
    if (!isset($arr[$p->name])) $params[] = $p->getDefaultValue();
    else $params[] = $arr[$p->name];
  }
  return $ref->invokeArgs( $params );
}
function make_named_array_function($func) {
  return function($arr) use ($func) {
    return call_user_func_named_array($func,$arr);
  };
}

call_user_func_named_array($x, ['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss
call_user_func_named_array($x, ['bar' => 'world']); //Only pass one parameter
call_user_func_named_array($x, []); //Will throw exception

$y = make_named_array_function($x);
$y(['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss
$y(['bar' => 'world']); //Only pass one parameter
$y([]); //Will throw exception



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template