Table of Contents
A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7
Home Backend Development PHP Tutorial A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7_PHP Tutorial

A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7_PHP Tutorial

Jul 12, 2016 am 08:49 AM
php php7 Function

A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7

Scalar type declaration

There are two modes: mandatory (default) and strict mode. The following type parameters are now available (either in forced or strict mode): string, int, float, and bool. In the old version, function parameter declarations could only be (Array $arr), (CLassName $obj), etc. Basic types such as Int, String, etc. could not be declared

<&#63;php
function check(int $bool){
var_dump($bool);
}
check(1);
check(true);

If there is no forced type conversion, int(1)bool(true) will be entered. After conversion, bool(true) bool(true)

will be output

Return value type declaration

PHP 7 adds support for return type declarations. The return type declaration specifies the type of the function's return value. The available types are the same as those available in the parameter declaration.

<&#63;php
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 routine will output:

Array
(
[0] => 6
[1] => 15
[2] => 24
)

null coalescing operator

There are a lot of cases where ternary expressions and isset() are used simultaneously in the project, and the syntactic sugar of null coalescing operator (??) is added. If the variable exists and is not NULL, it returns its own value, otherwise it returns the second operand.

Old version: isset($_GET['id']) ? $_GET[id] : err;

New version: $_GET['id'] ?? 'err';

Spaceship operator (combination comparison operator)

The spaceship operator is used to compare two expressions. When $a is less than, equal to or greater than $b it returns -1, 0 or 1 respectively

<&#63;php
// 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
&#63;>

Define constant array through define()

<&#63;php
define('ANIMALS', ['dog', 'cat', 'bird']);
echo ANIMALS[1]; // outputs "cat"

Anonymous class

Now supports instantiating an anonymous class through new class

<&#63;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;
}
});
var_dump($app->getLogger());

Unicode codepoint translation syntax

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

<&#63;php
echo “\u{9876}”

Old version output: u{9876}

New version input: Like

Closure::call()

Closure::call() now has better performance, a short and concise way to temporarily bind a method to the closure of the object and call it

<&#63;php
class Test{public $name = "lixuan";}
//PHP7和PHP5.6都可以
$getNameFunc = function(){return $this->name;};
$name = $getNameFunc->bindTo(new Test, 'Test');
echo $name();
//PHP7可以,PHP5.6报错
$getX = function() {return $this->name;};
echo $getX->call(new Test);

Provide filtering for unserialize()

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

<&#63;php
//将所有对象分为__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]);

IntlChar

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

<&#63;php
printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

The above routine will output:

10ffff
COMMERCIAL AT
bool(true)

Expected

The intention 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 old 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.

<&#63;php
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(false, new CustomError('Some error message'));

The above routine will output:

Fatal error: Uncaught CustomError: Some error message

Group use declarations

Classes, functions and constants imported from the same namespace can now be imported at once with a single use statement.

<&#63;php
//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};
&#63;>

intdiv()

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

<&#63;php
var_dump(intdiv(7, 2));

Output int(3)

CSPRNG

New two functions: random_bytes() and random_int(). Can encrypt and produce protected integers and strings. My poor translation, in short, random numbers have become safe.

random_bytes — Cryptographically protected pseudo-random strings

random_int — cryptographically protected pseudo-random integer

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.

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 the session

<&#63;php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);

The return value of the 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().

<&#63;php
function generator() {
yield 1;
yield 2;
yield 3;
return "a";
}
$generatorClass = ("generator")();
foreach ($generatorClass as $val) {
echo $val.” “;
}
echo $generatorClass->getReturn();

The output is: 1 2 3 a

生成器中引入其他生成器

在生成器中可以引入另一个或几个生成器,只需要写yield from functionName1

<&#63;php
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, " ";
}

输出:1 2 3 4 5 6

不兼容性

1、foreach不再改变内部数组指针

在PHP7之前,当数组通过 foreach 迭代时,数组指针会移动。现在开始,不再如此,见下面代码。

<&#63;php
$array = [0, 1, 2];
foreach ($array as &$val) {
var_dump(current($array));
}

PHP5输出:

int(1)
int(2)
bool(false)

PHP7输出:

int(0)
int(0)
int(0)

2、foreach通过引用遍历时,有更好的迭代特性

当使用引用遍历数组时,现在 foreach 在迭代中能更好的跟踪变化。例如,在迭代中添加一个迭代值到数组中,参考下面的代码:

<&#63;php
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}

PHP5输出:

int(0)

PHP7输出:

int(0)
int(1)

3、十六进制字符串不再被认为是数字

含十六进制字符串不再被认为是数字

<&#63;php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));

PHP5输出:

bool(true)
bool(true)
int(15)
string(2) "oo"

PHP7输出:

bool(false)
bool(false)
int(0)
Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

4、PHP7中被移除的函数

被移除的函数列表如下:

call_user_func() 和 call_user_func_array()从PHP 4.1.0开始被废弃。

已废弃的 mcrypt_generic_end() 函数已被移除,请使用mcrypt_generic_deinit()代替。

已废弃的 mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() 和 mcrypt_ofb() 函数已被移除。

set_magic_quotes_runtime(), 和它的别名 magic_quotes_runtime()已被移除. 它们在PHP 5.3.0中已经被废弃,并且 在in PHP 5.4.0也由于魔术引号的废弃而失去功能。

已废弃的 set_socket_blocking() 函数已被移除,请使用stream_set_blocking()代替。

dl()在 PHP-FPM 不再可用,在 CLI 和 embed SAPIs 中仍可用。

GD库中下列函数被移除:imagepsbbox()、imagepsencodefont()、imagepsextendfont()、imagepsfreefont()、imagepsloadfont()、imagepsslantfont()、imagepstext()

在配置文件php.ini中,always_populate_raw_post_data、asp_tags、xsl.security_prefs被移除了。

5、new 操作符创建的对象不能以引用方式赋值给变量

new 操作符创建的对象不能以引用方式赋值给变量

<&#63;php
class C {}
$c =& new C;

PHP5输出:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

PHP7输出:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

6、移除了 ASP 和 script PHP 标签

使用类似 ASP 的标签,以及 script 标签来区分 PHP 代码的方式被移除。 受到影响的标签有:<% %>、<%= %>、

7、从不匹配的上下文发起调用

在不匹配的上下文中以静态方式调用非静态方法, 在 PHP 5.6 中已经废弃, 但是在 PHP 7.0 中, 会导致被调用方法中未定义 $this 变量,以及此行为已经废弃的警告。

<&#63;php
class A {
public function test() { var_dump($this); }
}
// 注意:并没有从类 A 继承
class B {
public function callNonStaticMethodOfA() { A::test(); }
}
(new B)->callNonStaticMethodOfA();

PHP5输出:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

PHP7输出:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8
Notice: Undefined variable: this in /tmp/test.php on line 3

NULL

8、在数值溢出的时候,内部函数将会失败

将浮点数转换为整数的时候,如果浮点数值太大,导致无法以整数表达的情况下, 在之前的版本中,内部函数会直接将整数截断,并不会引发错误。 在 PHP 7.0 中,如果发生这种情况,会引发 E_WARNING 错误,并且返回 NULL。

9、JSON 扩展已经被 JSOND 取代

JSON 扩展已经被 JSOND 扩展取代。 对于数值的处理,有以下两点需要注意的: 第一,数值不能以点号(.)结束 (例如,数值 34. 必须写作 34.0 或 34)。 第二,如果使用科学计数法表示数值,e 前面必须不是点号(.) (例如,3.e3 必须写作 3.0e3 或 3e3)

10、INI 文件中 # 注释格式被移除

在配置文件INI文件中,不再支持以 # 开始的注释行, 请使用 ;(分号)来表示注释。 此变更适用于 php.ini 以及用 parse_ini_file() 和 parse_ini_string() 函数来处理的文件。

11、$HTTP_RAW_POST_DATA 被移除

不再提供 $HTTP_RAW_POST_DATA 变量。 请使用 php://input 作为替代。

12、yield 变更为右联接运算符

在使用 yield 关键字的时候,不再需要括号, 并且它变更为右联接操作符,其运算符优先级介于 print 和 => 之间。 这可能导致现有代码的行为发生改变。可以通过使用括号来消除歧义。

<&#63;php
echo yield -1;
// 在之前版本中会被解释为:
echo (yield) - 1;
// 现在,它将被解释为:
echo yield (-1);
yield $foo or die;
// 在之前版本中会被解释为:
yield ($foo or die);
// 现在,它将被解释为:
(yield $foo) or die;

以上所述是小编给大家介绍的浅析PHP7新功能及语法变化总结,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对帮客之家网站的支持!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1136631.htmlTechArticle浅析PHP7新功能及语法变化总结,浅析php7新功能语法 标量类型声明 有两种模式: 强制 (默认) 和 严格模式。 现在可以使用下列类型参数(无...
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Peak: How To Revive Players
1 months ago By DDD
PEAK How to Emote
4 weeks ago By Jack chen

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)

A Simple Guide to PHP Setup A Simple Guide to PHP Setup Jul 18, 2025 am 04:25 AM

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Improving Readability with Comments Improving Readability with Comments Jul 18, 2025 am 04:46 AM

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Writing Effective PHP Comments Writing Effective PHP Comments Jul 18, 2025 am 04:44 AM

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Mastering PHP Block Comments Mastering PHP Block Comments Jul 18, 2025 am 04:35 AM

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

See all articles