• 技术文章 >php教程 >php手册

    使用命名参数调用 PHP 函数

    2016-06-21 08:51:30原创444
      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



    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:nbsp 39 quot func named
    上一篇:PHP非常实用的上传类,上传效果在线演示 下一篇:为您介绍5个 PHP 安全措施
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• PHP -time(),date(),mktime()日期与时间函数库• php设计模式 Factory(工厂模式)• PHP5中的this,self和parent关键字详解• 修改mysql密码的方法• php session 预定义数组_php基础
    1/1

    PHP中文网