PHP将所有函数参数作为$ key => $ value数组?

时间:2011-01-13 09:14:28

标签: php

<?php
function register_template(){
    print_r(func_get_args());
    # the result was an array ( [0] => my template [1] => screenshot.png [2] => nice template .. ) 

}

register_template(     # unkown number of arguments
    $name = "my template",
    $screenshot = "screenshot.png",
    $description = "nice template .. "
)
?>

但是,我希望结果数组为$ key =&gt; $ value表单,$ key表示参数名称。

11 个答案:

答案 0 :(得分:13)

PHP不支持任意数量的命名参数。您可以在函数声明中决定固定数量的参数及其名称,也可以只获取值。

通常的方法是使用数组:

function register_template($args) {
    // use $args
}

register_template(array('name' => 'my template', ...));

答案 1 :(得分:12)

想要做同样的事情并且对已经给出的答案并不完全满意....

尝试将此添加到您的功能中 - &gt;

$reflector = new ReflectionClass(__CLASS__);
$parameters = $reflector->getMethod(__FUNCTION__)->getParameters();

$args = array();
foreach($parameters as $parameter)
{
    $args[$parameter->name] = ${$parameter->name};
}
print_r($args);

我没有考虑过试图让它成为你自己的功能但你可以打电话,但也许能够......

答案 2 :(得分:3)

没有参数名称这样的东西。 frobnicate($a = "b")不是带参数的调用语法,它只是一个后跟函数调用的赋值 - 一个用于代码文档的技巧,实际上并没有被语言考虑在内。

通常接受以下形式提供参数的关联数组:frobnicate(array('a' => 'b'))

答案 3 :(得分:2)

选项A)

<?php

function registerTemplateA() {
    // loop over every variable defined in the global scope,
    // such as those you created there when calling this function
    foreach($GLOBALS as $potentialKey => $potentialValue) {
        $valueArgs = func_get_args();
        if (in_array($potentialValue, $valueArgs)) {
            // this variable seems to match a _value_ you passed in
            $args[$potentialKey] = $potentialValue;
        }
    }
    // you now have an associative array in $args
    print_r($args);
}

registerTemplateA($name = "my template", $screenshot = "screenshot.png", $description = "nice template");

?>

选项B)

<?php

function registerTemplateB() {
    // passing in keys as args this time so we don't need to access global scope
    for ($i = 0; $i < func_num_args(); $i++) {
        // run following code on even args
        // (the even args are numbered as odd since it counts from zero)
        // `% 2` is a modulus operation (calculating remainder when dividing by 2)
        if ($i % 2 != 0) {
            $key = func_get_arg($i - 1);
            $value = func_get_arg($i);
            // join odd and even args together as key/value pairs
            $args[$key] = $value;
        }
    }
    // you now have an associative array in $args
    print_r($args);
}

registerTemplateB('name', 'my template', 'screenshot', 'screenshot.png', 'description', 'nice template');

?>

选项C)

<?php

function registerTemplateC($args) {
    // you now have an associative array in $args
    print_r($args);
}

registerTemplateC(array('name' => 'my template', 'screenshot' => 'screenshot.png', 'description' => 'nice template'));

?>

结论:选项C是最好的“最小代码”

(注意:这个答案是有效的PHP代码,在正确的位置打开和关闭标签,使用PHP 5.2.x进行测试,并且应该在PHP 4上运行...所以如果必须,请试试。)< / p>

答案 4 :(得分:1)

这很容易。只需将数组作为参数传递,然后稍后在函数内以$key => $value的形式访问它。

更新

这是我能想到的最好的

$vars = array("var1","var2"); //define the variable one extra time here
$$vars[0] = 'value1'; // or use $var1
$$vars[1] = 'value2'; // or use $var2

function myfunction() {
    global $vars;
    $fVars = func_get_args();
    foreach($fVars as $key=>$value) {
       $fvars[$vars[$key]] = $value;
       unset($fvar[$key]);
    }
    //now you have what you want var1=> value1
}

myfunction(array($$vars[0],$$vars[1]));

我还没有测试过...... BTW。但你应该明白这一点

答案 5 :(得分:1)

以地图名称获取功能参数=&gt; VALUE

function test($a,$b,$c){

  // result map   nameParam=>value
  $inMapParameters=[];

   //get values of parameters
  $fnValueParameters=func_get_args();

  $method = new \ReflectionMethod($this, 'test');


      foreach ($method->getParameters() as $index=>$param) {

            $name = $param->getName();

            if($fnValueParameters[$index]==null){continue;}

            $inMapParameters["$name"]=$fnValueParameters[$index];
        }

}

答案 6 :(得分:1)

class MyAwesomeClass
{
    public static function apple($kind, $weight, $color = 'green')
    {
        $args = self::funcGetNamedParams();
        print_r($args);
    }

    private static function funcGetNamedParams() {
        $func = debug_backtrace()[1]['function'];
        $args = debug_backtrace()[1]['args'];
        $reflector = new \ReflectionClass(__CLASS__);
        $params = [];
        foreach($reflector->getMethod($func)->getParameters() as $k => $parameter){
            $params[$parameter->name] = isset($args[$k]) ? $args[$k] : $parameter->getDefaultValue();
        }

        return $params;
    }
}

让我们测试一下吧!

MyAwesomeClass::apple('Granny Smith', 250);

输出:

Array
(
    [kind] => Granny Smith
    [weight] => 250
    [color] => green
)

答案 7 :(得分:0)

你不能,争论只是位置。也许你可以发送一个阵列?

<?php

function register_template(array $parameters) {
    var_dump($parameters);
}

register_template(# unkown number of arguments
    $name = "my template",
    $screenshot = "screenshot.png",
    $description = "nice template .. "
)


?>

答案 8 :(得分:0)

使用

function register_template($args){
    print_r ( $args ); // array (['name'] => 'my template' ...
    extract ($args);

    print $name; // my template
    print $screenshot;
}

register_templete ( array (
 "name" => "my template",
 "screenshot" => "screenshot.png",
 "description" => "nice template.."
));

答案 9 :(得分:0)

您可以通过 get_defined_vars ()完成此操作,但不要忘记该函数返回该函数范围内的每个变量。

例如:

<?php

function asd($q, $w, $rer){
    $test = '23ew';
    var_dump(get_defined_vars());
}

asd("qweqwe", 'ewrq', '43ewdsa');
?>

返回:

array(4) {
  ["q"]=>
  string(6) "qweqwe"
  ["w"]=>
  string(4) "ewrq"
  ["rer"]=>
  string(7) "43ewdsa"
  ["test"]=>
  string(4) "23ew"
}

答案 10 :(得分:-3)

使用它:

foreach(func_get_args() as $k => $v)
    echo $k . " => " . $v . "<BR/>";