Any PHP gurus out there? - Grin with cat attached — LiveJournal
Previous Entry Next Entry
Any PHP gurus out there? May. 21st, 2004 10:34 am
Update: Answered. Bugger.

Unfortunately, in PHP, you don't appear to be able to use default argument values when passing by reference, so you can't make pass-by-reference arguments optional.

eg, you can write:

function secondargoptional($something,$otherthing='default') { ... }


function secondargbyreference($something,&$otherthing) { ... }

but not

function secondargopptionalbyreference($something,&$otherthing='default') { ... }

(In PHP 4.3.4 at least)

Anyone got a workaround, or care to prove me wrong?

From: bootpunk
Date: May 21st, 2004 - 09:37 am (Link)
I've not used PHP in ages, and never really to that depth, so I haven't got any ready answers. I take it you have looked & posted about this to eg message boards at php.org?
From: wechsler
Date: May 21st, 2004 - 09:40 am (Link)
I'm spamming it to a few places, but thanks for the pointer.
From: deliberateblank
Date: May 21st, 2004 - 12:55 pm (Link)
I think you can do something similar by passing the function arguments inside an array, as references. The syntax isn't anywhere near as clean, but the effect is the same. Something like:

function test($argv)
  if (!is_array($argv)) {
    die("Invalid argument to test()");
  $argc = count($args);
  if ($a<2) {
    die("Not enough arguments to test()");
  printf("Got %d args<br /><br />\n", $a);
  $vals = array(NULL, NULL, "def3", 4); // default values
  for ( $i=0 ; $i<$argc ; $i++ ) {
    $vals[$i] = $argv[$i];
  // $vals is now our byval argument list with defaults filled
  echo "<br /><br />\n";
  // byrefs can be set by operating on $argv directly
  if ($argc>1) {
    $argv[1] = 999;

$x = 1;
$y = 2;

test(array($x, &$y));

printf("x=%d ; y=%d<br /><br />\n", $x, $y);

(I was hoping varargs would be useful here, but there seems no way to stop it from converting even literal refs into values.)