note 62803 added to functions.arguments
| From: | jcaplan at bogus dot amazon dot com | Date: | Thu, 09 Mar 2006 23:11:02 +0000 |
| Subject: | note 62803 added to functions.arguments | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-105171@lists.php.net to get a copy of this message | ||
In function calls, PHP clearly distinguishes between missing arguments and present but empty
arguments. Thus:
<?php
function f( $x = 4 ) { echo $x . "\\n"; }
f(); // prints 4
f( null ); // prints blank line
f( $y ); // $y undefined, prints blank line
?>
The utility of the optional argument feature is thus somewhat diminished. Suppose you want to call
the function f many times from function g, allowing the caller of g to specify if f should be called
with a specific value or with its default value:
<?php
function f( $x = 4 ) {echo $x . "\\n"; }
// option 1: cut and paste the default value from f's interface into g's
function g( $x = 4 ) { f( $x ); f( $x ); }
// option 2: branch based on input to g
function g( $x = null ) { if ( !isset( $x ) ) { f(); f() } else { f( $x ); f( $x ); } }
?>
Both options suck.
The best approach, it seems to me, is to always use a sentinel like null as the default value of an
optional argument. This way, callers like g and g's clients have many options, and
furthermore, callers always know how to omit arguments so they can omit one in the middle of the
parameter list.
<?php
function f( $x = null ) { if ( !isset( $x ) ) $x = 4; echo $x . "\\n"; }
function g( $x = null ) { f( $x ); f( $x ); }
f(); // prints 4
f( null ); // prints 4
f( $y ); // $y undefined, prints 4
g(); // prints 4 twice
g( null ); // prints 4 twice
g( 5 ); // prints 5 twice
?>
----
Server IP: 66.163.161.117
Probable Submitter: 207.171.180.101
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/functions.arguments.php
Edit -- http://master.php.net/note/edit/62803
Del: integrated -- http://master.php.net/note/delete/62803/integrated
Del: useless -- http://master.php.net/note/delete/62803/useless
Del: bad code -- http://master.php.net/note/delete/62803/bad+code
Del: spam -- http://master.php.net/note/delete/62803/spam
Del: non-english -- http://master.php.net/note/delete/62803/non-english
Del: in docs -- http://master.php.net/note/delete/62803/in+docs
Del: other reasons-- http://master.php.net/note/delete/62803
Reject -- http://master.php.net/note/reject/62803
Search -- http://master.php.net/manage/user-notes.php