Home  >  Article  >  Backend Development  >  What are the new features in each version of PHP7.x?

What are the new features in each version of PHP7.x?

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-06-07 09:24:261934browse

This article will introduce to you the new features of each version of PHP7.x. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

What are the new features in each version of PHP7.x?

Preface

Last month my colleague saw me writing

$a = $a ?? '';

and asked me what this way of writing is, is there any other way of writing it? I said this is a writing method that is only available in PHP7 and above. Don’t you know? He said he didn't know.

I muttered in my heart and planned to start writing this blog.

PHP7 should be a modern PHP in addition to the basics. Because in PHP7, strong type definitions and some grammatical writing methods, such as combined comparison operators, define() can define arrays and other features. The formal introduction begins below, starting with PHP7.0. New versions will be added in the future, and they will be added one after another.

Okay, let’s start

PHP 7.0

Scalar type declaration

What is a scalar type?

Four scalar types:

boolean (Boolean type)

integer (integer type)

float (floating point type, also known as As double)

string (string)

Two composite types:

array (array)

object (object)

Resource is a special variable that stores a reference to an external resource. Resources are created and used through specialized functions. Resource type variables are special handles for opening files, database connections, graphics canvas areas, etc.

To put it more simply, a scalar type is a data type that defines a variable.

In php5, there are class names, interfaces, arrays and callback functions. In PHP, strings, integers, floats, and bools have been added. Let's take an example below. See the example for everything

function typeInt(int $a)
{
    echo $a;
}

typeInt('sad');
// 运行,他讲会报错 Fatal error: Uncaught TypeError: Argument 1 passed to type() must be of the type integer, string given

Here, we define that $a must be of type int. If string is passed in the type function, an error will be reported. Let's modify the above code.

function typeString(string $a)
{
    echo $a;
}

typeString('sad'); 
//sad

Return value type declaration

The return value of a function method can be defined. For example, if a certain function of mine must return an int type, it will be defined. If you return an int, an error will be reported if you return a string. As follows

<?php

function returnArray(): array
{

    return [1, 2, 3, 4];
}

print_r(returnArray());
/*Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
*/

What happens when we define an array and return string or other types?

Then he will report an error such as

function returnErrorArray(): array
{

    return &#39;1456546&#39;;
}

print_r(returnErrorArray());
/*
Array
Fatal error: Uncaught TypeError: Return value of returnArray() must be of the type array, string returned in 
*/

null merge operator

Due to the large number of simultaneous use of ternary expressions and isset() in daily use , we added the syntactic sugar of null coalescing operator (??). If the variable exists and is not NULL, it returns its own value, otherwise it returns its second operand.

<?php

$username = $_GET[&#39;user&#39;] ?? &#39;nobody&#39;;
//这两个是等效的  当不存在user 则返回?? 后面的参数

$username = isset($_GET[&#39;user&#39;]) ? $_GET[&#39;user&#39;] : &#39;nobody&#39;;

?>

Spaceship operator

// 整数
echo 1 <=> 1; // 0 当左边等于右边的时候,返回0
echo 1 <=> 2; // -1  当左边小于右边,返回-1
echo 2 <=> 1; // 1  当左边大于右边,返回1

// 浮点数
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
 
// 字符串
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

define Define array

In versions before PHP7, define was not able to define arrays, but now it is possible. For example,

define(&#39;ANIMALS&#39;, [
    &#39;dog&#39;,
    &#39;cat&#39;,
    &#39;bird&#39;
]);

echo ANIMALS[1]; // 输出 "cat"

use method batch import

// PHP 7 之前的代码
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;

// PHP 7+ 及更高版本的代码
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Unicode codepoint translation syntax

echo "\u{aa}"; //ª
echo "\u{0000aa}";  //ª  
echo "\u{9999}"; //香

Anonymous class

<?php
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;
    }
});

PHP 7.1

Nullable type

The types of parameters and return values ​​can now be allowed to be empty by adding a question mark before the type. When this feature is enabled, the parameters passed in or the result returned by the function are either of the given type or null .

<?php

function testReturn(): ?string
{
    return &#39;elePHPant&#39;;
}

var_dump(testReturn()); //string(10) "elePHPant"

function testReturn(): ?string
{
    return null;
}

var_dump(testReturn()); //NULL

function test(?string $name)
{
    var_dump($name);
}

test(&#39;elePHPant&#39;); //string(10) "elePHPant"
test(null); //NULL
test(); //Uncaught Error: Too few arguments to function test(), 0 passed in...

void

Added a void-returning type, such as

<?php
function swap(&$left, &$right) : void
{
    if ($left === $right) {
        return;
    }

    $tmp = $left;
    $left = $right;
    $right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

Multiple exception capture processing

This function is quite commonly used in daily development Among them

<?php
try {
    // some code
} catch (FirstException | SecondException $e) {  //用 | 来捕获FirstException异常,或者SecondException 异常
  
}

PHP 7.2

PHP7.2 is the least new feature of the PHP7 series

Allows trailing commas in grouped namespaces

For example,

<?php

use Foo\Bar\{
    Foo,
    Bar,
    Baz,
};

allows overriding of abstract methods

<?php

abstract class A
{
    abstract function test(string $s);
}
abstract class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    abstract function test($s) : int;
}

New object types

<?php

function test(object $obj) : object  //这里 可以输入对象
{
    return new SplQueue();
}

test(new StdClass());

PHP 7.3

PHP7.3 There is nothing big at the syntax level Change.

PHP 7.4

Class attributes support type declaration

Congratulations on PHP taking another step towards strong typing

<?php
class User {
    public int $id;
    public string $name;
}
?>

Arrow function

Arrow Functions provides a shorthand syntax for defining functions using implicit by-value scope binding. It’s similar to the arrow function of JS, but with an fn. A wave of complaints

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

Null merge operator support method

<?php
$array[&#39;key&#39;] ??= computeDefault();
// 类似与这个
if (!isset($array[&#39;key&#39;])) {
    $array[&#39;key&#39;] = computeDefault();
}
?>
Recommended learning:

php video tutorial######

The above is the detailed content of What are the new features in each version of PHP7.x?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete