PHP and ?? operator

As some people know, C # has a very useful operator ??that evaluates and returns the expression on the right if the expression on the left is NULL. This is very useful for providing default values, for example:

int spaces = readSetting("spaces") ?? 5;

If it readSettingcannot be found "spaces"and returns null, the variable spaceswill contain the default value 5.

You can do almost the same thing in JavaScript and Ruby using the operator ||, as in

var spaces = readSetting("spaces") || 5;

although you could not have 0as a value spacesin JavaScript in this case and falsein Ruby and JavaScript.

PHP has an operator or, and although it does not work as ||in a sense that it does not return an expression on the right, it can still be useful here:

$spaces = readSetting('spaces') or $spaces = 5;

with a note that ""both are "0"also considered both falsein PHP in addition to false, 0and nullin most languages.

The question is, should the construction be used from above? Does it have side effects besides treating a large class of characters as false? And is there a better design commonly used and recommended by the PHP community for this task?

+5
source share
5 answers

, , PHP, (, "0" , ).

, readSettings , , . null. :

$spaces = readSettings('spaces');
if (null === $spaces) {
    $spaces = 5;
}

, $ , :

$spaces = readSettings('spaces');
if (empty($spaces)) {    // or:  if (!$spaces) {
    $spaces = 5;
}

( ):

$spaces = readSettings('space') ? readSettings('space') : 5;
$spaces = ($x = readSettings('space')) ? $x : 5;  // UGLY!

, 0 $spaces!

Zen of Python:

, .

$default readSettings():

function readSettings($key, $default=null) {
    return isset($settings[$key]) ? $settings[$key] : $default;
}

$spaces = readSettings('spaces', 5); 
+6

PHP 5.3.0 : true: false, :

$spaces = readSettings('spaces') ?: 5;

, PHP 5.3.0 - - ( ), , - , , , out!

, :

http://www.sitepoint.com/article/whats-new-php-5-3/

+6

?

$spaces = ($tmp=readSettings('space')) ? $tmp : 5;

, :

$spaces = ($spaces=readSettings('space')) ? $spaces : 5;
+4

, false null, , "0", "false", :

$spaces = readSetting('spaces');
if($spaces == null || $spaces === false) $spaces = 5;

=== PHP , "0", "" false, , , .

+1

PHP 7 ?? Null-

(??) , (). , , NULL; .

<?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'; 
?>

http://php.net/manual/en/migration70.new-features.php

+1

All Articles