三元運算子 – 馬永占 譯

來源:互聯網
上載者:User

著作權聲明:原創作品,允許轉載,轉載時請務必以超連結形式標明文章原始出版、作者資訊和本聲明。否則將追究法律責任。http://blog.csdn.net/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.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.