Home Backend Development PHP Tutorial Summary of new syntax features in PHP7.0 and php7.1

Summary of new syntax features in PHP7.0 and php7.1

Aug 07, 2018 am 11:15 AM

This article brings you a summary of the new grammatical features in PHP7.0 and php7.1. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

New features of php7.0:

1, empty merge operator ( ??)

Simplified judgment

$param = $_GET['param'] ?? 1;
Copy after login

is equivalent to:

$param = isset($_GET['param']) ? $_GET['param'] : 1;
Copy after login

2. Two types of variable type declaration

Mode: mandatory (default) and strict mode
Types: string, int, float and bool

function add(int $a) { 
    return 1+$a; 
} 
var_dump(add(2);
Copy after login

3, return value type declaration

Function and anonymous function You can specify the type of the return value

function show(): array { 
    return [1,2,3,4]; 
}

function arraysSum(array ...$arrays): array {
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
Copy after login

4. Spaceship operator (combined comparison operator)

The spaceship operator is used to compare two expressions. It returns -1, 0 or 1 when a is greater than, equal to or less than b respectively. The principle of comparison follows PHP's regular 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
Copy after login

5. Anonymous classes

Now supports instantiating an anonymous class through new class, which can be used to replace some complete classes that are "burn after use" definition.

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;
    }
});
var_dump($app->getLogger());
Copy after login

6. Unicode codepoint translation syntax

This accepts a Unicode codepoint in hexadecimal form and prints out a UTF-8 surrounded by double quotes or heredoc Encoded format string. Any valid codepoint is accepted, and the leading 0 can be omitted.

 echo "\u{9876}"
Copy after login

Old version output: \u{9876}
New version input: Top

7, Closure::call()

Closure: :call() now has better performance and is a short and concise way to temporarily bind a method to a closure on an object and call it.

class Test {
    public $name = "lixuan";
}

//PHP7和PHP5.6都可以
$getNameFunc = function () {
    return $this->name;
};
$name = $getNameFunc->bindTo(new Test, &#39;Test&#39;);
echo $name();
//PHP7可以,PHP5.6报错
$getX = function () {
    return $this->name;
};
echo $getX->call(new Test);
Copy after login

8. Provide filtering for unserialize()

This feature is designed to provide a safer way to unpack unreliable data. It prevents potential code injection through whitelisting.

//将所有对象分为__PHP_Incomplete_Class对象
$data = unserialize($foo, ["allowed_classes" => false]);
//将所有对象分为__PHP_Incomplete_Class 对象 除了ClassName1和ClassName2
$data = unserialize($foo, ["allowed_classes" => ["ClassName1", "ClassName2"]);
//默认行为,和 unserialize($foo)相同
$data = unserialize($foo, ["allowed_classes" => true]);
Copy after login

9. IntlChar

The newly added IntlChar class is designed to expose more ICU functions. This class itself defines many static methods for operating unicode characters from multiple character sets. Intl is a Pecl extension. It needs to be compiled into PHP before use. You can also apt-get/yum/port install php5-intl

printf(&#39;%x&#39;, IntlChar::CODEPOINT_MAX);
echo IntlChar::charName(&#39;@&#39;);
var_dump(IntlChar::ispunct(&#39;!&#39;));
Copy after login

The above routine will output:
10ffff
COMMERCIAL AT
bool(true)

10. Expectation

Expectation is to use backwards and enhance the previous assert() method. It makes enabling assertions cost-effective in production and provides the ability to throw specific exceptions when assertions fail. The older version of the API will continue to be maintained for compatibility purposes, and assert() is now a language construct that allows the first argument to be an expression, not just a string to be calculated or a boolean to be tested.

ini_set(&#39;assert.exception&#39;, 1);
class CustomError extends AssertionError {}
assert(false, new CustomError(&#39;Some error message&#39;));
Copy after login

The above routine will output:
Fatal error: Uncaught CustomError: Some error message

11、Group use declarations

From the same Namespace imported classes, functions, and constants can now be imported all at once with a single use statement.

//PHP7之前
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;

// PHP7之后
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};
Copy after login

12. intp()

Receives two parameters as dividend and divisor, and returns the integer part of their division result.

var_dump(intp(7, 2));
Copy after login

Output int(3)

13, CSPRNG

Add two new functions: random_bytes() and random_int(). Can be encrypted Produce protected integers and strings. In short, random numbers become safe.
random_bytes — A cryptographically protected pseudo-random string
random_int — A cryptographically protected pseudo-random integer

14, preg_replace_callback_array()

A new function preg_replace_callback_array() has been added. Using this function can make the code more elegant when using the preg_replace_callback() function. Before PHP7, the callback function would be called for every regular expression, and the callback function was contaminated on some branches.

15. Session options

Now, the session_start() function can receive an array as a parameter, which can override the session configuration items in php.ini.
For example, set cache_limiter to private and close the session immediately after reading it.

session_start([&#39;cache_limiter&#39; => &#39;private&#39;,
               &#39;read_and_close&#39; => true,
]);
Copy after login

16. Return value of generator

The concept of generator is introduced in PHP5.5. Each time the generator function is executed, it gets a value identified by yield. In PHP7, when the generator iteration is completed, the return value of the generator function can be obtained. Obtained through Generator::getReturn().

function generator() {
    yield 1;
    yield 2;
    yield 3;
    return "a";
}

$generatorClass = ("generator")();
foreach ($generatorClass as $val) {
    echo $val ." ";

}
echo $generatorClass->getReturn();
Copy after login

The output is: 1 2 3 a

17. Introduce other generators into the generator

You can introduce another or several generators into the generator A generator, just write yield from functionName1

function generator1() {
    yield 1;
    yield 2;
    yield from generator2();
    yield from generator3();
}

function generator2() {
    yield 3;
    yield 4;
}

function generator3() {
    yield 5;
    yield 6;
}

foreach (generator1() as $val) {
    echo $val, " ";
}
Copy after login

Output: 1 2 3 4 5 6

18. Define a constant array through define()

define(&#39;ANIMALS&#39;, [&#39;dog&#39;, &#39;cat&#39;, &#39;bird&#39;]);
echo ANIMALS[1]; // outputs "cat"
Copy after login

New features of php7.1:

1. Nullable type

type NULL is now allowed. When this feature is enabled, the parameters passed in or the result returned by the function are either of the given type or null. You can make a type nullable by preceding it with a question mark.

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

The above routine will output:

string(5) "tpunt"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...
Copy after login

2、Void 函数

在PHP 7 中引入的其他返回值类型的基础上,一个新的返回值类型void被引入。 返回值声明为 void 类型的方法要么干脆省去 return 语句,要么使用一个空的 return 语句。 对于 void 函数来说,null 不是一个合法的返回值。

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);
Copy after login

以上例程会输出:

null
int(2)
int(1)
Copy after login

试图去获取一个 void 方法的返回值会得到 null ,并且不会产生任何警告。这么做的原因是不想影响更高层次的方法。

3、短数组语法 Symmetric array destructuring

短数组语法([])现在可以用于将数组的值赋给一些变量(包括在foreach中)。 这种方式使从数组中提取值变得更为容易。

$data = [
    [&#39;id&#39; => 1, &#39;name&#39; => &#39;Tom&#39;],
    [&#39;id&#39; => 2, &#39;name&#39; => &#39;Fred&#39;],
];
while ([&#39;id&#39; => $id, &#39;name&#39; => $name] = $data) {
    // logic here with $id and $name
}
Copy after login

4、类常量可见性

现在起支持设置类常量的可见性。

class ConstDemo
{
    const PUBLIC_CONST_A = 1;
    public const PUBLIC_CONST_B = 2;
    protected const PROTECTED_CONST = 3;
    private const PRIVATE_CONST = 4;
}
Copy after login

5、iterable 伪类

现在引入了一个新的被称为iterable的伪类 (与callable类似)。 这可以被用在参数或者返回值类型中,它代表接受数组或者实现了Traversable接口的对象。 至于子类,当用作参数时,子类可以收紧父类的iterable类型到array 或一个实现了Traversable的对象。对于返回值,子类可以拓宽父类的 array或对象返回值类型到iterable。

function iterator(iterable $iter) {
    foreach ($iter as $val) {
        //
    }
}
Copy after login

6、多异常捕获处理

一个catch语句块现在可以通过管道字符(|)来实现多个异常的捕获。 这对于需要同时处理来自不同类的不同异常时很有用。

try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
} catch (\Exception $e) {
    // ...
}
Copy after login

7、list()现在支持键名

现在list()支持在它内部去指定键名。这意味着它可以将任意类型的数组 都赋值给一些变量(与短数组语法类似)

$data = [
    [&#39;id&#39; => 1, &#39;name&#39; => &#39;Tom&#39;],
    [&#39;id&#39; => 2, &#39;name&#39; => &#39;Fred&#39;],
];
while (list(&#39;id&#39; => $id, &#39;name&#39; => $name) = $data) {
    // logic here with $id and $name
}
Copy after login

8、支持为负的字符串偏移量

现在所有接偏移量的内置的基于字符串的函数都支持接受负数作为偏移量,包括数组解引用操作符([]).

var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));
Copy after login

以上例程会输出:

string (1) "e"
int(3)
Copy after login

9、ext/openssl 支持 AEAD

通过给openssl_encrypt()和openssl_decrypt() 添加额外参数,现在支持了AEAD (模式 GCM and CCM)。
通过 Closure::fromCallable() 将callables转为闭包
Closure新增了一个静态方法,用于将callable快速地 转为一个Closure 对象。

class Test {
    public function exposeFunction() {
        return Closure::fromCallable([$this, &#39;privateFunction&#39;]);
    }
    private function privateFunction($param) {
        var_dump($param);
    }
}
$privFunc = (new Test)->exposeFunction();
$privFunc(&#39;some value&#39;);
Copy after login

以上例程会输出:

string(10) "some value"
Copy after login

10、异步信号处理 Asynchronous signal handling

A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).
增加了一个新函数 pcntl_async_signals()来处理异步信号,不需要再使用ticks(它会增加占用资源)

pcntl_async_signals(true); // turn on async signals
pcntl_signal(SIGHUP,  function($sig) {
    echo "SIGHUP\n";
});
posix_kill(posix_getpid(), SIGHUP);
Copy after login

以上例程会输出:

SIGHUP
Copy after login

11、HTTP/2 服务器推送支持 ext/curl

Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUST_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied. 
翻译: 
对于服务器推送支持添加到curl扩展(需要7.46及以上版本)。 
可以通过用新的CURLMOPT_PUSHFUNCTION常量 让curl_multi_setopt()函数使用。 
也增加了常量CURL_PUST_OK和CURL_PUSH_DENY,可以批准或拒绝 服务器推送回调的执行

相关文章推荐:

php7和php5有什么不同之处?php5与php7之间的对比

PHP新特性:finally关键字的用法

The above is the detailed content of Summary of new syntax features in PHP7.0 and php7.1. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles