版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。http://blog.youkuaiyun.com/mayongzhan - 马永占,myz,mayongzhan
三元运算符
phpbuilder.com网站介绍了一篇使PHP更高效的方法 - 三元运算符。
在使用前检查变量是单调乏味的,而且难免会有些遗漏,导致整个程序出现错误或者使程序非常的脆弱。有一个最简单的办 法解决这个问题,使用三元运算符。它可以让你检查是否存在一个变量(或检查该变量有一个有效值) ,并指派一个值。这是非常有用的方法,你所处理的$_GET,$_POST,¥_SESSION 等等变量的时候,因为你不知道它是否真的有值传递过来,如果它不存在,你就需要指定一个默认值。这里是三元条件运算符的格式:
CONDITION ? VALUE IF TRUE : VALUE IF FALSE
条件?值(条件为真的情况):值(条件为假的情况)
这里是一个例子:
<?PHP
$id = isset($_GET['id']) ? $_GET['id'] : false;
?>
一条代码替代了很多的代码。首先,它使用isset ()函数,检查$_GET['id']是否存在。如果$_GET['id']确实存在,它将返回它的价值。但是,如果它不存在,条件即为假,这时返回的是 false。$id的值取决于$_GET['id']是否存在。所以,基本上,如果$_GET['id']存在,$id=$_GET['id'],反之$ id=false。
这对程序员是有益的,可以帮助开发者尽量避免使用if语句。
PHPBuilder.com: The Ternary Conditional Operator
The PHPBuilder.com site has a quick reminder about a handy little bit of functionality PHP has to make evaluations quicker - the ternary operator.
Checking for variables before you use them can be a tedious process, and this step is often missed out in PHP code, leading to masses of PHP Notice errors and possibly leaving the application vulnerable. However, there is a simple solution to this problem, something called the ternary conditional operator. This allows you to check for the existence of a variable (or check that the variable has a valid value) and assign a value accordingly. This is very useful when you are dealing with $_GET, $_POST, $_SESSION etc. variables, because you don't know whether the incoming variable will exist, and if it doesn't you might want to assign a default value. Here is the format of the ternary conditional operator:
CONDITION ? VALUE IF TRUE : VALUE IF FALSE
Here is an example to hopefully put this into context:
<?php
$id = isset($_GET['id']) ? $_GET['id'] : false;
?>
This one line of code does a surprisingly large amount. Firstly, it uses the isset() function to check if $_GET['id'] exists. If $_GET['id'] does exist it simply returns its value. However, if it does not exist the operator returns false. The value that the operator returns is then assigned to the variable $id. So, basically, if $_GET['id'] exists then $id = $_GET['id'], however if it does not exist then $id = false
The operator can be useful in a number of applications, and helps you to avoid loads of unnecessary if statements.
PHP三元运算符
本文介绍了PHP中三元运算符的使用方法及其优势。通过一个简单的例子展示了如何使用三元运算符来简化代码,减少不必要的if语句,提高程序效率。
886

被折叠的 条评论
为什么被折叠?



