|
Posted by Schraalhans Keukenmeester on 05/12/07 14:00
At Thu, 10 May 2007 13:44:16 -0700, Mike P2 let his monkeys type:
> I wasn't going to suggest using the ternary operator because Dean said
> he is a beginner and is following a book. I assume that book has this
> planned out and will introduce that operator at a later time, and the
> purpose of the example he is having trouble with is to introduce him
> to some other concept. I just didn't want to confuse him.
>
> Also, Toby A Inkster, that function is a good idea, but it will result
> in a notice anyway if the variable is undefined. It will issue a
> notice anyway because when you put the undefined variable in the
> function call, php is trying to pass the value of that variable, so it
> throws a notice right there. It could be otherwise written with
> strings passed:
>
> function ifsetor2()
> {
> $fArgv = array();
> $fArgv = func_get_args();
> $fArgc = func_num_args() - 1;
>
> for( $i = 0; $i < $fArgc; ++$i )
> {
> $glStr = ( $s = strpos( $fArgv[$i], '[' ) ) !== false
> ? substr( $fArgv[$i], 0, $s )
> : $fArgv[$i];
> $glStr = ( $s = strpos( $glStr, '.' ) ) !== false
> ? substr( $glStr, 0, $s )
> : $glStr;
>
> eval( "global \$$glStr;
> \$stuff = isset( \${$fArgv[$i]} )
> ? \${$fArgv[$i]}
> : false;" );
>
> if( $stuff !== false )
> return $stuff;
> }
>
> return $fArgv[$fArgc];
> }
>
> This will allow you to use more than one candidate as you mentioned,
> and PHP will not issue a notice this way. The parameters are N strings
> that are the names of variables (without $, and can be an array, but
> then the index [if a string] needs to be in single or double quotes),
> and finally a string to return if none are set. This new function
> should work with fields of objects, too.
>
> example:
> echo ifsetor2( '_GET["search"]', '_GET['submit']', 'none' );
>
> -Mike PII
Toby's version of ifsetor works fine without notices as long as the
function is modified slightly. (My version was called is_if_set, what's
in a name ;-))
function ifsetor (&$var,$alternative=null) {
return (isset($var)) $var : $alternative;
}
The notice comes from argument copying, so we simply don't...
For a multiple length variable list the alternatives given elsewhere in
this thread offer more flexibility of course.
Just my 2cts.
Sh.
Navigation:
[Reply to this message]
|