動機
記性不好,寫一遍筆記比較記得起來
解決方案
1. $param = isset($_GET['param']) ? $_GET['param'] : 'default'; 2. $result = $x ?: 'default'; 3. $param = $_GET['param'] ?? 'default';
實驗
1
通常在檢查變數用的
$param = isset($_GET['param']) ? $_GET['param'] : 'default';檢查GET param變數。
如果有值,就用傳進來的。
如果沒有,就用 'default'
2
$result = $x ?: 'default';更簡單的寫法,在php 5.3以後才能用
如果x是null,則返回default
簡單寫個測試用的就知道了
file: test2.php <?php $x = null; $result = $x ?: 'default'; echo $result."\n"; $x = "abc"; $result = $x ?: 'default'; echo $result."\n"; ?> root@raspberrypi:~# /opt/php/bin/php test2.php default abc
3
$param = $_GET['param'] ?? 'default';如果想要更潮一點,可以用php7的語法
官方的Null coalescing operator解釋
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.節錄一下程式碼部分
<?php // Fetches the value of $_GET['user'] and returns 'nobody' // if it does not exist. $username = $_GET['user'] ?? 'nobody'; // This is equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; // Coalescing can be chained: this will return the first // defined value out of $_GET['user'], $_POST['user'], and // 'nobody'. $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody'; ?>一樣做個小實驗
file: test3.php <?php $username = $a ?? $b ?? 'nobody'; echo $username."\n"; $c = "weij var C"; $username2 = $c ?? $d ?? 'nobody'; echo $username2."\n"; $f = "weij var F"; $username3 = $e ?? $f ?? 'nobody'; echo $username3."\n"; $g = "weij var G"; $h = "weij var H"; $username3 = $g ?? $h ?? 'nobody'; echo $username3."\n"; ?> root@raspberrypi:~# /opt/php/bin/php test3.php nobody weij var C weij var F weij var G從結果可以看出,如果不是null,在第一個就會返回答案
如果一路都是null,則直接返回nobody
這個糖果有點甜吶 XD
留言
張貼留言