On 20/Oct/10 2:58 PM, Richard Quadling wrote:
Hello.

Take the following simple code.

<?php
function foo($var1, $var2 = 2, $var3 = 3) {
  echo "$var1, $var2, $var3\n";
}

foo(10); // 10, 2, 3
foo(10, 20); // 10, 20, 3
foo(10, 20, 30); // 10, 20, 30
foo(10, null, 30); // 10, , 30
foo(10,, 30); // Parse error.
?>

According to the manual

A variable is considered to be null if it has not been set to any value yet [1].
By default, function arguments are passed by value [2].
When using default arguments, any defaults should be on the right side
of any non-default arguments. [3]


 From this, the question I have is what do I pass when I want to use
the default, WITHOUT having to supply the default value itself.

On the surface, null should work. Null (according to [1]) is
specifically saying that there is no value. But it is being
interpreted as a value.

I'm guessing the reason for null being interpreted as a value is
really that the supplied argument count is used and any unsupplied
arguments are defaulted.

But null isn't a value ... that seems to be REALLY important to me.
But from userland it is a value. Just a really odd one.

I would argue that by having a null in the arguments, the intent is to
NOT supply a value and have the default value used in the function.


Possible solutions.

1 - Do nothing in core and implement is_null() checking to reinstate
the default value.

function foo($var1, $var2 = 2, $var3 = 3) {
  $var2 = is_null($var2) ? 2 : $var2;
  $var3 = is_null($var3) ? 3 : $var3;
  echo "$var1, $var2, $var3\n";
}


2 - Allow null to be supplied and have the default value be used for
the argument.

foo(10, null, 30); // would output 10, 2, 30


3 - New keyword of default or void to specifically indicate the intent
to use the default value for the argument.

foo(10, default, 30); // would output 10, 2, 30


4 - Allow missing arguments to default.

foo(10,, 30); // Parse error.



Option 4 would probably be the worse one to go for. Looking any number
of languages that support defaults and you will see code like ...

someFunction(param1,,,,,param7,,,,param11)

sort of thing.



Option 3, whilst does clearly indicate the intent, does introduce a
new keyword. As a non core dev, I'm guessing we end up with naming
conflicts. And something called "default" is probably going to be a
big one. "Void" also.

But using something like _ (yep, underscore), could be a solution here [4].



Option 2, after probably having to reject option 3, would be my
choice. I want null to REALLY mean nothing. Just like it would be in
foo(10).



Option 1 is what I have to do at the moment.

Option 5: Implement named parameters?

--
IonuČ› G. Stan  |  http://igstan.ro

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to