Dougnoel: niels is correct. What C and C++ call "short circuit evaluation" is simply called "lazy evaluation" in other languages. He's not making a value judgement.
Mods: please remove clueless commentary.
Strutture di controllo
Indice dei contenuti
- else
- elseif
- Sintassi alternativa per le strutture di controllo
- while
- do-while
- for
- foreach
- break
- continue
- switch
- declare
- return
- require
- include
- require_once
- include_once
Qualsiasi script PHP è costituito da una serie di istruzioni. Una istruzione può essere un'assegnazione, una chiamata di funzione, un loop, una istruzione condizionale che non fa nulla (istruzione vuota). Le istruzioni terminano con un punto e virgola. Inoltre, le istruzioni si possono raggruppare in blocchi di istruzioni racchiudendole tra parentesi graffa. Un gruppo di istruzioni è, a sua volta, un'istruzione. Il presente capitolo descrive i differenti tipi di istruzioni.
if
Il costrutto if è una delle più importanti caratteristiche di qualsiasi linguaggio, incluso PHP. Permette l'esecuzione condizionata di frammenti di codice. La struttura di controllo if di PHP è simile a quella del linguaggio C:
<?php
if (expression)
istruzione
?>
Come descritto nella sezione sulle espressioni, espressione restiruirà il suo valore booleano. Se espressione vale TRUE, PHP eseguirà istruzione, e se essa vale FALSE - la ignorerà. Più informazioni riguardo i valori valutati FALSE possono essere trovati nella sezione 'Conversione in booleano' .
L'esempio che segue visualizzerà a è maggiore di b se $a sarà maggiore di $b:
<?php
if ($a > $b)
echo "a è maggiore di b";
?>
Spesso sarà necessario eseguire più di una istruzione condizionale. Naturalmente non è necessario, utilizzare una singola clausola if per ciascuna istruzione. Si possono raggruppare diverse istruzioni in un singolo gruppo di istruzioni. Per esempio, il codice che segue visualizzerà a è maggiore di b se $a è maggiore di $b, e successivamente assegnerà il valore della variabile $a alla variabile $b:
<?php
if ($a > $b) {
echo "a è maggiore di b";
$b = $a;
}
?>
Si possono annidare indefinitamente istruzioni if, la qual cosa fornisce piena flessibilità per l'esecuzione di istruzioni condizionali in diversi punti del programma.
Strutture di controllo
19-Dec-2007 08:21
30-Aug-2007 03:45
Sinured: You can do the same thing with logical OR; if the first test is true, the second will never be executed.
<?PHP
if (empty($user_id) || in_array($user_id, $banned_list))
{
exit();
}
?>
02-Aug-2007 02:59
As mentioned below, PHP stops evaluating expressions as soon as the result is clear. So a nice shortcut for if-statements is logical AND -- if the left expression is false, then the right expression can’t possibly change the result anymore, so it’s not executed.
<?php
/* defines MYAPP_DIR if not already defined */
if (!defined('MYAPP_DIR')) {
define('MYAPP_DIR', dirname(getcwd()));
}
/* the same */
!defined('MYAPP_DIR') && define('MYAPP_DIR', dirname(getcwd()));
?>
09-Mar-2007 11:53
@mongoose643
dougnoel was actually trying to provide a good example of how the if function automatically evaluates to false and goes no further if the first condition in an if expression fails can be used to optimize a script. In his example not everyone is an admin, and not all admins can delete. In his script it is an optimized failsafe to check if someone is an admin and has delete permissions while not wasting script time.
01-Mar-2007 10:03
@simplyduh
>Duh, both are booleans in the above case, and its obvious
>that checking one boolean is better than checking 2.
>if ($has_delete_permissions) would work better :)
I read dougnoel's post. He was providing an example of a BAD example. The last line in his post suggests that you NOT check for both - only the admin. So actually what he meant to check for is whether or not they are an admin. If so then they automatically have delete permissions - therefore it may be possible that no variable named "$has_delete_permissions" exists. The resulting statement would be as follows:
if($is_admin)
{
//Statements to delete stuff go here.
}
06-May-2006 09:29
Further response to Niels:
It's not laziness, it's optimization. It saves CPUs cycles. However, it's good to know, as it allows you to optimize your code when writing. For example, when determining if someone has permissions to delete an object, you can do something like the following:
if ($is_admin && $has_delete_permissions)
If only an admin can have those permissions, there's no need to check for the permissions if the user is not an admin.
26-Dec-2004 11:49
For the people that know C: php is lazy when evaluating expressions. That is, as soon as it knows the outcome, it'll stop processing.
<?php
if ( FALSE && some_function() )
echo "something";
// some_function() will not be called, since php knows that it will never have to execute the if-block
?>
This comes in nice in situations like this:
<?php
if ( file_exists($filename) && filemtime($filename) > time() )
do_something();
// filemtime will never give an file-not-found-error, since php will stop parsing as soon as file_exists returns FALSE
?>
