note 88258 added to functions.arguments

From: Date: Sat, 17 Jan 2009 20:48:55 +0000
Subject: note 88258 added to functions.arguments
Groups: php.notes 
Request: Send a blank email to php-notes+get-149370@lists.php.net to get a copy of this message
There is a nice trick to emulate variables/function calls/etc as default values: <?php $myVar = "Using a variable as a default value!"; function myFunction($myArgument=null) { if($myArgument===null) $myArgument = $GLOBALS["myVar"]; echo $myArgument; } // Outputs "Hello World!": myFunction("Hello World!"); // Outputs "Using a variable as a default value!": myFunction(); // Outputs the same again: myFunction(null); // Outputs "Changing the variable affects the function!": $myVar = "Changing the variable affects the function!"; myFunction(); ?> In general, you define the default value as null (or whatever constant you like), and then check for that value at the start of the function, computing the actual default if needed, before using the argument for actual work. Building upon this, it's also easy to provide fallback behaviors when the argument given is not valid: simply put a default that is known to be invalid in the prototype, and then check for general validity instead of a specific value: if the argument is not valid (either not given, so the default is used, or an invalid value was given), the function computes a (valid) default to use. ---- Server IP: 69.147.83.197 Probable Submitter: 78.152.253.101 ---- Manual Page -- http://www.php.net/manual/en/functions.arguments.php Edit -- https://master.php.net/note/edit/88258 Del: integrated -- https://master.php.net/note/delete/88258/integrated Del: useless -- https://master.php.net/note/delete/88258/useless Del: bad code -- https://master.php.net/note/delete/88258/bad+code Del: spam -- https://master.php.net/note/delete/88258/spam Del: non-english -- https://master.php.net/note/delete/88258/non-english Del: in docs -- https://master.php.net/note/delete/88258/in+docs Del: other reasons-- https://master.php.net/note/delete/88258 Reject -- https://master.php.net/note/reject/88258 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#149370) next »