[Gllug] mySQL PHP
Dave Cridland
dave at cridland.net
Wed Jul 11 15:01:44 UTC 2001
On 11 Jul 2001 12:41:47 +0000, Bruce Richardson wrote:
>
> On 7/11/01, 11:25:10 AM, Dave Cridland <dave at cridland.net> wrote
> regarding Re: [Gllug] mySQL PHP:
>
>
> > On 10 Jul 2001 19:38:15 +0100, Bruce Richardson wrote:
> > > On Tue, Jul 10, 2001 at 07:10:43PM +0100, Bruce Richardson wrote:
> > > > $var1 = $var1 ? $var : "default value";
> > >
> > > Sorry:
> > >
> > > $var1 = $var1 ? $var1 : "default value";
> > >
> > > --
> > > Bruce
>
> > Although, in my quest for code that tells the programmer what's really
> > going on, I'd be more specific:
>
> > if( !isset( $var ) ) {
> > $var = $var_default;
> > }
>
> No. Your code does not do the same as mine. Your code tests to see
> if $var is set - my code tests whether $var has a TRUE value (i.e. any
> value other than FALSE) and the test fails if $var1 either has a value
> of FALSE or is unset. A variable with a value of FALSE is set and
> your code misses it.
>
> If ($var) { $var = $var_default }
>
> is correct.
Well, if you want to be pedantic, then:
- $var is assumed to be coming from a form variable, or similar.
- Your rewritten test does exactly the opposite of your original code.
- If $var is 0, '', false, or unset, then you will overwrite with a
default value. '' and unset are both fine to test for, whereas a form
might reasonably treat an explicitly entered value of 0 as distinct from
a default value.
> Besides, not only is the ?: operator used in quite a few C-style
> languages but it is explained in the introductory section of the PHP
> manual. Your quest is for code which will be understood by people who
> haven't bothered to learn the language.
The trigraph is fine - I was just typing it out in full.
However, given that the lack of entry of a variable often means more
than simply using a default value, I'm inclined to use a full if
conditional, with the braces for stylistic reasons. (Otherwise, I've
seen other programmers simply add a line to the conditional without
adding the braces later.)
I'd imagine the usual handling of a form variable to look like:
global $HTTP_POST_VARS; // Because I'd assume we were in a function.
if( !isset( $HTTP_POST_VARS['var'] ) || !strlen( $HTTP_POST_VARS['var']
) ) {
// Either:
$var = SOME_SUITABLE_DEFAULT;
// Or:
my_add_error( 'Var was not specified in the form' );
}
For checking whether a form had been submitted, so as to know whether to
display a blank form, I'd do:
global $HTTP_POST_VARS;
if( isset( $HTTP_POST_VARS[ 'submit_button_name' ] ) ) {
process_form();
} else {
display_form();
}
I realise it's unlikely that the form submit button would have a value
which evaluated to false in a conditional, but neither does it hurt, and
it saves PHP from actually making the evaluation, making the code
marginally more efficient, IMHO.
Dave.
--
Gllug mailing list - Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug
More information about the GLLUG
mailing list