The null coalescing operator php

PHP RFC: Unary null coalescing operator

PHP 7.0 introduced the Null Coalescing Operator ( ?? ), which provides a convenient, more concise alternative to isset ( ) or an explicit NULL check when retrieving the values of variables, properties and object members. Specifically, it provides the short syntax $foo ?? $bar which returns $foo if it exists and is not NULL , or otherwise $bar . This is useful when, for example, retrieving data from query parameters or a configuration file.

One use of the ?? operator is not to retrieve a value per se, but to check its value without worrying about whether it exists, for instance $_GET [ «action» ] ?? NULL === «submit» lets you check if there is a query parameter named action that is set to submit , which is considerably shorter and less redundant than typing out isset ( $_GET [ «action» ] ) && $_GET [ «action» ] === «submit» .

It is this latter use-case that this RFC concerns. While ?? NULL is significantly better than the full expression using isset ( ) , it is still redundant, since we have to provide some arbitrary default value. A shorter alternative would be to use the error-suppression operator ( @ ), but it is slow and considered bad practice.

Читайте также:  Событие при нажатии кнопки python

Thus, this RFC proposes a small tweak to ?? .

Proposal

This RFC proposes a unary version of ?? , which would be equivalent to the normal binary version where the second argument is NULL . That is, $foo ?? would now be valid, and behave identically to $foo ?? NULL in every respect.

The unary form of ?? would provide a faster, non-proscribed alternative to @ for retrieving possibly-unset variables. It would also provide a concise, non-redundant way to check the value of a possibly-unset variable.

One practical use is optional request parameters:

if ($_POST["action"]?? === "submit") { // Form submission logic } else { // Form display logic }

Another is optional options in, say, a configuration object, or an “options bag” parameter:

if ($optionsBag->safeMode?? === TRUE) { // Safe mode } else { // Not safe }

Backward Incompatible Changes

There is an ambiguity in the case where unary ?? is followed by an operator that can be either unary or binary, i.e. $a ?? + $b and $a ?? — $b . These continue to be parsed the same ( $a ?? ( + $b ) , $a ?? ( — $b ) ), meaning there is no backwards-compatibility break.

Proposed PHP Version(s)

Next PHP 7.x, which would be PHP 7.2 at the time of writing.

RFC Impact

To SAPIs, Existing Extensions and Opcache

There is no effect on any of these, with the exception of extensions inspecting the AST, for which the unary ?? is indistinguishable from ?? NULL .

Unaffected PHP Functionality

The behaviour of binary ?? is unchanged, as is isset ( ) .

Future Scope

Vote

This is a simple language change which should only require a 2/3 majority vote on whether or not to approve it.

Voting started 2017-07-11 and ends 2017-07-18 ended 2017-07-18.

Patches and Tests

A php-src patch, including a test, can be found here: https://github.com/php/php-src/pull/2589

A patch for the language specification, including the same test, can be found here: https://github.com/php/php-langspec/pull/197

Implementation

After the project is implemented, this section should contain

Источник

The null coalescing operator php

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings ( string ), integers ( int ), floating-point numbers ( float ), and booleans ( bool ). They augment the other types introduced in PHP 5: class names, interfaces, array and callable .

// Coercive mode
function sumOfInts ( int . $ints )
return array_sum ( $ints );
>

var_dump ( sumOfInts ( 2 , ‘3’ , 4.1 ));

The above example will output:

To enable strict mode, a single declare directive must be placed at the top of the file. This means that the strictness of typing for scalars is configured on a per-file basis. This directive not only affects the type declarations of parameters, but also a function’s return type (see return type declarations, built-in PHP functions, and functions from loaded extensions.

Full documentation and examples of scalar type declarations can be found in the type declaration reference.

Return type declarations

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

function arraysSum (array . $arrays ): array
return array_map (function(array $array ): int return array_sum ( $array );
>, $arrays );
>

print_r ( arraysSum ([ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]));

The above example will output:

Full documentation and examples of return type declarations can be found in the return type declarations. reference.

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.

// 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’ ;
?>

Spaceship operator

The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b . Comparisons are performed according to PHP’s usual type comparison rules.

// Integers
echo 1 1 ; // 0
echo 1 2 ; // -1
echo 2 1 ; // 1

// Floats
echo 1.5 1.5 ; // 0
echo 1.5 2.5 ; // -1
echo 2.5 1.5 ; // 1

// Strings
echo «a» «a» ; // 0
echo «a» «b» ; // -1
echo «b» «a» ; // 1
?>

Constant arrays using define()

Array constants can now be defined with define() . In PHP 5.6, they could only be defined with const .

echo ANIMALS [ 1 ]; // outputs «cat»
?>

Anonymous classes

Support for anonymous classes has been added via new class . These can be used in place of full class definitions for throwaway objects:

interface Logger public function log ( string $msg );
>

class Application private $logger ;

public function getLogger (): Logger return $this -> logger ;
>

public function setLogger ( Logger $logger ) $this -> logger = $logger ;
>
>

$app = new Application ;
$app -> setLogger (new class implements Logger public function log ( string $msg ) echo $msg ;
>
>);

The above example will output:

Full documentation can be found in the anonymous class reference.

Unicode codepoint escape syntax

This takes a Unicode codepoint in hexadecimal form, and outputs that codepoint in UTF-8 to a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0’s being optional.

The above example will output:

ª ª (same as before but with optional leading 0's) 香

Closure::call()

Closure::call() is a more performant, shorthand way of temporarily binding an object scope to a closure and invoking it.

// Pre PHP 7 code
$getX = function() x ;>;
$getXCB = $getX -> bindTo (new A , ‘A’ ); // intermediate closure
echo $getXCB ();

// PHP 7+ code
$getX = function() x ;>;
echo $getX -> call (new A );

The above example will output:

Filtered unserialize()

This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.

// converts all objects into __PHP_Incomplete_Class object
$data = unserialize ( $foo , [ «allowed_classes» => false ]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize ( $foo , [ «allowed_classes» => [ «MyClass» , «MyClass2» ]]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize ( $foo , [ «allowed_classes» => true ]);

IntlChar

The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.

printf ( ‘%x’ , IntlChar :: CODEPOINT_MAX );
echo IntlChar :: charName ( ‘@’ );
var_dump ( IntlChar :: ispunct ( ‘!’ ));

The above example will output:

10ffff COMMERCIAL AT bool(true)

In order to use this class, the Intl extension must be installed.

Expectations

Expectations are a backwards compatible enhancement to the older assert() function. They allow for zero-cost assertions in production code, and provide the ability to throw custom exceptions when the assertion fails.

While the old API continues to be maintained for compatibility, assert() is now a language construct, allowing the first parameter to be an expression rather than just a string to be evaluated or a bool value to be tested.

class CustomError extends AssertionError <>

assert ( false , new CustomError ( ‘Some error message’ ));
?>

The above example will output:

Fatal error: Uncaught CustomError: Some error message

Full details on this feature, including how to configure it in both development and production environments, can be found on the manual page of the assert() language construct.

Group use declarations

Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement.

// Pre PHP 7 code
use some \namespace\ ClassA ;
use some \namespace\ ClassB ;
use some \namespace\ ClassC as C ;

use function some \namespace\ fn_a ;
use function some \namespace\ fn_b ;
use function some \namespace\ fn_c ;

use const some \namespace\ ConstA ;
use const some \namespace\ ConstB ;
use const some \namespace\ ConstC ;

Generator Return Expressions

This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the new Generator::getReturn() method, which may only be used once the generator has finished yielding values.

$gen = (function() yield 1 ;
yield 2 ;

foreach ( $gen as $val ) echo $val , PHP_EOL ;
>

echo $gen -> getReturn (), PHP_EOL ;

The above example will output:

Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.

Generator delegation

Generators can now delegate to another generator, Traversable object or array automatically, without needing to write boilerplate in the outermost generator by using the yield from construct.

function gen2 ()
yield 3 ;
yield 4 ;
>

foreach ( gen () as $val )
echo $val , PHP_EOL ;
>
?>

The above example will output:

Integer division with intdiv()

The new intdiv() function performs an integer division of its operands and returns it.

The above example will output:

Session options

session_start() now accepts an array of options that override the session configuration directives normally set in php.ini.

These options have also been expanded to support session.lazy_write, which is on by default and causes PHP to only overwrite any session file if the session data has changed, and read_and_close , which is an option that can only be passed to session_start() to indicate that the session data should be read and then the session should immediately be closed unchanged.

For example, to set session.cache_limiter to private and immediately close the session after reading it:

preg_replace_callback_array()

The new preg_replace_callback_array() function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function to be polluted with lots of branching.

Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.

CSPRNG Functions

Two new functions have been added to generate cryptographically secure integers and strings in a cross platform way: random_bytes() and random_int() .

list() can always unpack objects implementing ArrayAccess

Previously, list() was not guaranteed to operate correctly with objects implementing ArrayAccess . This has been fixed.

Other Features

Источник

Оцените статью