使用具名引數調用 PHP 函數

來源:互聯網
上載者:User

  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 函數,代碼如下:

<?php

$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

 

  更新:很感謝一些熱心的貢獻者做的一些改進:

 

 <?php

$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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.