Basem
Basem

Reputation: 442

PHP get all function arguments as $key => $value array?

<?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 .. "
)
?>

BUT , I want the result array as $key => $value form , $key represents the parameter name.

Upvotes: 8

Views: 17578

Answers (11)

Mesuti
Mesuti

Reputation: 908

You can do it via get_defined_vars() but you should not forget this function return every variable in the scope of the function.

For example:

<?php

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

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

Return:

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

Upvotes: 1

Sergey Onishchenko
Sergey Onishchenko

Reputation: 7851

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;
    }
}

Let's test it!

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

The output:

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

Upvotes: 1

dnocode
dnocode

Reputation: 2088

GET FUNCTION PARAMETERS AS MAP NAME=>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];
        }

}

Upvotes: 1

user1462432
user1462432

Reputation: 253

Wanted to do the same thing and wasn't completely satisfied with the answers already given....

Try adding this into your function ->

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

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

I haven't thought about trying to make this it's own function yet that you can just call, but might be able to...

Upvotes: 14

deizel.
deizel.

Reputation: 11212

Option 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");

?>

Option 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');

?>

Option 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'));

?>

Conclusion: option C is the best "for minimum code"

(Note: this answer is valid PHP code, with open and close tags in the correct places, tested using PHP 5.2.x and should run on PHP 4 also... so give it a try if you must.)

Upvotes: 2

Starx
Starx

Reputation: 78991

It's easy. Just pass the array as the parameter instead then later access it as $key => $value inside the function.

UPDATE

This was the best I could think of

$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]));

I haven't tested it...BTW. But you should get the point

Upvotes: 1

Anush Prem
Anush Prem

Reputation: 1481

Use

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.."
));

Upvotes: 0

Xavier Barbosa
Xavier Barbosa

Reputation: 3947

you can't, arguments are only positionnal. maybe you can send an array ?

<?php

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

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


?>

Upvotes: 0

Victor Nicollet
Victor Nicollet

Reputation: 24577

There is no such thing as a parameter name. frobnicate($a = "b") is not a call-with-parameter syntax, it's merely an assignment followed by a function call - a trick used for code documentation, not actually taken into account by the language.

It is commonly accepted to instead provide an associative array of parameters in the form: frobnicate(array('a' => 'b'))

Upvotes: 3

Amir
Amir

Reputation: 820

use this :

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

Upvotes: -3

deceze
deceze

Reputation: 522135

PHP does not support an arbitrary number of named parameters. You either decide on a fixed number of parameters and their names in the function declaration or you can only get values.

The usual way around this is to use an array:

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

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

Upvotes: 15

Related Questions