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); 
2
  • The "normal" PHP way is to override not-used arguments with NULL, as you have done. Commented Jul 16, 2012 at 9:26
  • You may want to use func_get_args? Commented Jul 16, 2012 at 9:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 - that's not what stackoverflow.com/questions/680368/… seems to say.
@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.
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.
-2

No, param3 would be treated as param2.

You could pass a hash as in:

$myhash = array('param1'=>'someval','param3'=>'someval');
foo($myhash);

1 Comment

Use name not indexs

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.