开发者

PHP: using => operator without an array

Is there a way to use the PHP => ope开发者_如何学Gorator (?) without using the array() "constructor"?

To be specific, I want to create a function that will get a list of keys and values without wrapping it into an array:

function keysAndValues($items) {
    /* ... */
}

keysAndValues(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);

Instead of

keysAndValues(array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
));

Is there a way to do this?


These would be named arguments. Nope, not possible in PHP. You will have to wrap an array() around them.

If it's not the array that's bothering you but the fact that you have to work with an array inside the function, try

function my_function($array)
{
extract($array);
...
if (isset($number)) echo "Number is: ".$number;
}

to unpack the options into the function's scope:

my_function(array("number" => "one")); // Will output "Number is: one"

it saves the hassle of unpacking them one by one using foreach().


The closest thing you can get to what you want is by using dynamic arguments.

Using this tutorial/overview as a base, here is a hack to provide a potential solution:

function keysAndValues() {
   for($i = 0 ; $i < func_num_args(); $i++) {
       list($key, $value) = explode('=>', func_get_arg($i));
       // Do something with the $key and $value
   }
}

It would then be called like this:

keysAndValues('key1=>value1','key2=>value2','key3=>value3');
keysAndValues('key1=>value1');

Basically, you can have any amount of parameters... they are dynamic!


well, specifically, the '=>' operator denotes the key, value pair inside an array, so there's really no reason to use it outside the array constructor.

that said, it is used inside things like a 'foreach' loop to grab the key and value for each item in an array

foreach ($arr as $key=>$val)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜