0

Possible Duplicate:
PHP Optional Parameters - specify parameter value by name?

Can I call a function as with first and third parameter only this in PHP5?
Is there another way to specify the params order?

function foo($param1=null, $param2=null, $param3=null) {}

foo($param1, $param3); 

Instead of:

foo($param1, null, $param3); 
Community
  • 1
  • 1
Samson
  • 2,801
  • 7
  • 37
  • 55

2 Answers2

0

Not directly, but you can write something like:

function foo($args)
{
    print "param1 : " . $args["param1"] . "\n";
    print "param2 : " . $args["param2"] . "\n";
    print "param3 : " . $args["param3"] . "\n";
}

foo(array("param1" => $param1, "param3" => $param3)); 

instead if you want to permit optional usage like that.

Flexo
  • 87,323
  • 22
  • 191
  • 272
  • 1
    It has several disadvantages, to use an array instead of individual arguments. It's harder to document; another developer wouldn't have a useful auto-completion in their IDE; you need more conditional expressions (`if/else`) to check whether an argument was set; you can't use PHPs type hinting feature… In short: it's a really bad idea to pass several, individual arguments as a single array. – feeela Jul 16 '12 at 09:25
  • @feeela - that's not what http://stackoverflow.com/questions/680368/emulating-named-function-parameters-in-php-good-or-bad-idea seems to say. – Flexo Jul 16 '12 at 09:28
  • @Flexo Well, it seems that you only have read one if the answers there. In the long term, the downsides weight heavier than the advantages – especially when building a larger application which is to be maintained over years. The accepted answer doesn't even answer the question "Emulating named function parameters in PHP, good or bad idea?". It rather makes a statement on whether to use the extracted array vars or the array itself, when using an array for all arguments. – feeela Jul 16 '12 at 09:37
  • This is indeed a pretty bad idea, and it should be avoided unless you have a real need for it. If your function has so many parameters that you need to start naming them, you're doing it wrong. Nevermind that the syntax is awful and it's a very bad approximation of named parameters, a real feature that some languages support. – user229044 Jul 18 '12 at 04:16
-2

No, param3 would be treated as param2.

You could pass a hash as in:

$myhash = array('param1'=>'someval','param3'=>'someval');
foo($myhash);
George Kagan
  • 5,913
  • 8
  • 46
  • 50