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();
}
?>
控制结构
Table of Contents
- else
- elseif
- 流程控制的替代语法
- while
- do-while
- for
- foreach
- break
- continue
- switch
- declare
- return
- require
- include
- require_once
- include_once
任何 PHP 脚本都是由一系列语句构成的。一条语句可以是一个赋值语句,一个函数调用,一个循环,一个条件语句或者甚至是一个什么也不做的语句(空语句)。语句通常以分号结束。此外,还可以用花括号将一组语句封装成一个语句组。语句组本身可以当作是一行语句。本章讲述了各种语句类型。
if
if 结构是很多语言包括 PHP 在内最重要的特性之一,它允许按照条件执行代码片段。PHP 的 if 结构和 C 语言相似:
<?php
if (expr)
statement
?>
如同在表达式一章中定义的,expr 按照布尔求值。如果 expr 的值为 TRUE,PHP 将执行 statement,如果值为 FALSE - 将忽略 statement。有关哪些值被视为 FALSE 的更多信息参见转换为布尔值一节。
如果 $a 大于 $b,则以下例子将显示 a is bigger than b:
<?php
if ($a > $b)
echo "a is bigger than b";
?>
经常需要按照条件执行不止一条语句,当然并不需要给每条语句都加上一个 if 子句。可以将这些语句放入语句组中。例如,如果 $a 大于 $b,以下代码将显示 a is bigger than b 并且将 $a 的值赋给 $b:
<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>
if 语句可以无限层地嵌套在其它 if 语句中,这给程序的不同部分的条件执行提供了充分的弹性。
控制结构
wintermute
30-Aug-2007 03:45
30-Aug-2007 03:45
Sinured
02-Aug-2007 02:59
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()));
?>
dougnoel
06-May-2006 09:29
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.
niels dot laukens at tijd dot com
26-Dec-2004 11:49
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
?>
