Re: Using default argument values in the middle of the argument list

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sat, 02 Jun 2012 17:13:55 +0200, Matijn Woudt <tijnema@xxxxxxxxx> wrote:


Hi Oliver,

I think the example at [1] demonstrates that it is possible, but it
also notes that it is pretty useless. Why are you interested in this?

- Matijn

[1] http://www.php.net/manual/en/functions.arguments.php#example-153

Hi,

Thanx for your response.

PHP class type hints are bit more restrictive than in say Java
since it does not accept null as a value of a class. This provides
great guarantees, however, sometimes it is desirable to allow null as well.

This can be done using:

function func ( Classname $a = null )

Unfortunately, according to documentation this will work only at the end of
parameter list. So this restriction force you to put nullable arguments at
the end of argument list or not use type hints at all. In the worst case
scenario you have to choose between use of illogical order of arguments,
reimplementation of type hinting for arguments that comes after the
nullable one or use no type hinting at all for nullable arguments:

function func ( Classname $last, Classname $first = null ) {
  ...
}

or

function func ( Classname $first = null, Classname $last = null ) {
  if ( $last === null ) throw new InvalidArgumentException;
  ...
}

or

function func ( $first, Classname $last ) {
if ( !( $first instanceof Classname ) ) throw new InvalidArgumentException;
  ...
}

This is not ideal especially if the desired solution seems to work:

function func ( Classname $first = null, Classname $last ) {
  ...
}

This function expects exactly two arguments. The second one is supposed to be an instance of Classname and the first one may be an instance of Classname or null.

This might be useless for primitive values since any default value you can define can be provided from the outside as well. But, it is definitely not useless for objects since you can not pass null value as an argument that requires an object of some class. As far as i can tell this can emulate Java style object type handling
when you needed it. I would be glad to rely on such a behavior.

-- Oliver

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux