April 16, 2012

php function arguments

Question by Clint Chaney

I don’t know how or where I got this idea in my head but for some reason I thought this was possible. Obviously after testing it doesn’t work, but is there a way to make it work? I want to set $value2 without having to enter anything at all for $value1.

function test($value1 = 1, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test($value2 = 3);

// output
Value 1: 3
Value 2: 2

Answer by rami

What you’re trying to do is called “keyword arguments” or “named arguments” and is not available in PHP in contrast to other scripting languages like Python.

If you have functions with hundreds of parameters and really want to achieve a more flexible solution than what PHP comes with, you could build your own workaround with arrays or objects, maybe in conjunction with func_get_args(). But this obviously isn’t as beautiful as real keyword arguments.

Answer by Starx

Its not entirely possible the way you want.

Simply,

function test($value1 = null, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test(NULL, $value2 = 3);

Or, Use array as parameters

function test($array) {

if(isset($array['value1'])) echo 'Value 1: '.$array['value1'].'<br />';
if(isset($array['value2'])) echo 'Value 2: '.$array['value2'].'<br />';

}

test(array('value2' => 3));

Update:

My another attempt

function test() {
  $args = func_get_args();
  $count = count($args);
  if($count==1) { test1Arg($args[0]); }
  elseif($count == 2) { test2Arg($args[0],$args[1]); }
  else { //void; }
}

function test1Arg($arg1) {
   //Do something for only one argument
}
function test2Arg($arg1,$arg2) {
   //Do something for two args
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!