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();
}
?>
第 16章制御構造
全ての PHP スクリプトは、一連の文からなります。 文としては、代入、関数コール、ループ、条件文、そして何もしない文(空の文) さえ使用することができます。 文は、通常セミコロンで終了します。加えて、文は、中括弧によるグループ文で カプセル化することによりグループ化することが可能です。 グループ文は、同時に文にもなります。 本章では、様々な文の型が記述されています。
if
if 構文は、PHP を含む全ての言語において最も重要な 機能の一つです。 この構文は、命令の条件実行を可能にします。 PHP では、C 言語に似た次のような if 構文が使用されます。
式のセクションで 記述したように式は論理値で評価されます。 式が TRUE と評価された場合、 PHP は文を実行します。FALSE と評価された場合は、これを無視します。どのような値が FALSE と評価されるかについては論理値への変換 を参照してください。
以下の例は、$a が $b より大きい場合、aはbより大きい を表示します。
条件分岐させたい文が一つ以上ある場合もしばしばあります。 もちろん、各々の文をif 文で括る必要はありません。 代わりに、複数の文をグループ化することができます。 例えば、このコードは、$a が $b よりも大きい場合に aはbよりも大きいを表示し、 $a の値を $b に 代入します。
if文は、他のif文の中で無限に入れ子にできます。 これは、プログラムの様々な部分の条件付実行について 完全な柔軟性を提供します。
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()));
?>
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.
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
?>
