optional reference parameter to function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

optional reference parameter to function

Post by Weirdan »

is there way to have optional reference parameter in function signature? something like:

Code: Select all

function some_func(&$param = null) {
  if( is_null($param) ) {
       // do something...
  } else {
       // do something else...
  }
}
// or
function some_other_func() {
   if( func_num_args() ) {
       $param =& func_get_arg(0);
        // do something...
   } else {
        // do something else...
   }
}
first example yields parsing error, second copies parameter instead of getting reference to it.

Any ideas?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

actually, one can do:

Code: Select all

function some_func( $param = array() ) {
   if( isset($param[0]) ) {
       $param =& $param[0];
        // do something
   } else {
       // do something else
   }
}
$arr = arrray();
some_func(array(&$arr));
var_dump($arr);
but is there more elegant solution?
I don't like this mess in function signature ;)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

If there isn't I haven't found it. That's the only way I think.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply