Php function parameters can be passed in a different order, as defined in the declaration

Suppose I have a function / method F () that takes 3 parameters $ A, $ B and $ C, defined like this.

function F($A,$B,$C){ ... } 

Suppose I don’t want to follow the order in which the parameters are passed, can I make such a call instead?

 F($C=3,$A=1,$B=1); 

instead

 F(1,2,3) 
+7
source share
6 answers

Absolutely not.

One way you could go about in unordered arguments is to accept an associative array:

 function F($params) { if(!is_array($params)) return false; //do something with $params['A'], etc... } 

Then you can call it like this:

 F(array('C' => 3, 'A' => 1, 'B' => 1)); 
+10
source

PHP has no named arguments, so the short answer is no. There are two solutions that I can find, although not all are fantastic.

You can define your function to accept its arguments as an array, for example this :

 function image($img) { $tag = '<img src="' . $img['src'] . '" '; $tag .= 'alt="' . ($img['alt'] ? $img['alt'] : '') .'">'; return $tag; } $image = image(array('src' => 'cow.png', 'alt' => 'cows say moo')); $image = image(array('src' => 'pig.jpeg')); 

This method, unfortunately, requires changing your function, and as a result, I do not like it. Another option is to use this wrapper class , which allows you to use named arguments in one of the following ways:

 $obj->method(array('key' => 'value', 'key2' => 'value2')); $obj->method(':key = value', ':key2 = value2'); 
+2
source

No, but you can pass an associative array to handle this:

 f(array('C'=>3, 'A'=>1, 'B'=>1)); 

and then access it:

 function f($obj) { $c = $obj['C']; } 
+1
source

No, not using standp php syntax.

Of course, there are always tricks for this, for example, if you yourself define this function, you can do something like

 F(array('C'=>3, 'A'=>1, 'B'=>1)); 

But for this you, of course, will have to rewrite the original function so that it accepts the array as arguments, and not just accept the arguments themselves.

0
source

No, you can’t. Something I did for functions where many parameters are optional, or I don't want the order to matter, I should use a single array parameter instead.

 function myfunc( $options ) { $one = $options['one']; $two = $options['two']; // etc. } 
0
source

Taken from here ...

If you prefer to use named arguments for your functions (so you don't have to worry about the order of variable argument lists), you can make this PERL style with anonymous arrays:

 <?php function foo($args) { print "named_arg1 : " . $args["named_arg1"] . "\n"; print "named_arg2 : " . $args["named_arg2"] . "\n"; } foo(array("named_arg1" => "arg1_value", "named_arg2" => "arg2_value")); ?> 

will output:

 named_arg1 : arg1_value named_arg2 : arg2_value 
0
source

All Articles