-- Hector Virgen <[email protected]> wrote
(on Thursday, 26 August 2010, 11:11 AM -0700):
> PHP is a loosely-typed language, meaning that the empty string '' will
> evaluate
> to false unless you do strict comparisons (=== and !==). For example:
>
> $test = FALSE;
>
> if ('' != $test) {
> // this executes because of loose typing
> }
>
> if ('' !== $test) {
> // this doesn't execute because of strict comparison
> }
Actually, it _will_ execute. If $test is not '', it returns a boolean
true, otherwise a boolean false.
Both of the above will execute. The first differs from the second in
that if $test evaluates to any empty value ('', array(), false, null),
the expression will evaluate to false, otherwise true.
The real question is why we use conditions like the following in ZF:
(null === $value)
('' == $value)
('foo' == $value)
etc.
THe main reason you see these constructs is because it's an easy way to
ensure you don't accidently perform assignment instead of a comparison
-- there's a difference between ('foo' = $value) and ('foo' == $value),
and PHP's parser will catch the problem with the first, but wouldn't if
you inverted it ($value = 'foo').
> When testing function return values that may return a number or FALSE,
> it is best to use strict comparisons:
>
> while(false !== ($attribute = $result->fetch_assoc())) {
> ...
> }
Stricly speaking, the above is _not_ necessary.
However, if you don't do the strict comparison, and $attribute evaluates
to an empty string, null, or 0, the condition will fail -- even if there
are more results available. This is the main reason to use the more
verbose form as Hector displays above.
> On Thu, Aug 26, 2010 at 10:54 AM, Daniel Latter <[email protected]> wrote:
>
> Hi All,
>
> forgive me for the simplistic question but looking through ZF source I
> see if statements structured like so:
>
> if ('' === $value) {
> ..
> }
>
> is this just to protect against $value being empty?
>
> Consequently, would I be better doing this:
>
> while(false != ($attribute = $result->fetch_assoc())) {
> ...
> }
>
> instead of:
>
> while($attribute = $result->fetch_assoc()) {
> ..
> }
>
> TIA
>
> Dan
>
>
--
Matthew Weier O'Phinney
Project Lead | [email protected]
Zend Framework | http://framework.zend.com/
PGP key: http://framework.zend.com/zf-matthew-pgp-key.asc