Home  >  Article  >  Backend Development  >  New features added in PHP 7

New features added in PHP 7

不言
不言Original
2018-05-03 14:08:351082browse

This article mainly introduces the newly added features of PHP 7, which has a certain reference value. Now I share it with everyone. Friends in need can refer to this

Scalar type declaration

PHP 7 The formal parameter type declaration of functions in can now be scalar. In PHP 5 it can only be a class name, interface, array or callable (PHP5.4, that is, it can be a function, including anonymous function ), now you can also use string, int, float and bool are gone.

<?php
// 强制模式
function sumOfInts(int...$ints)
{
    return array_sum($ints);
}
 
var_dump(sumOfInts(2,&#39;3&#39;,4.1));

The above example will output:

int(9)

It should be noted that the strict mode problem mentioned above also applies here: in forced mode (default, which is forced type conversion), there will still be errors that do not meet expectations. The parameters are forced to type conversion, and in strict mode, a fatal error of TypeError will be triggered.


##Return value type declaration

PHP 7 Added support for return type declarations. Similar to the parameter type declaration, the return type declaration specifies the type of function return value. The available types are the same as those available in the parameter declaration.

<?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 example will output:

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


NULL Coalescing operator

Due to the large number of simultaneous uses of ternary expressions and isset in daily use () situation, NULL The merging operator makes the variable exist and the value is not NULL, It will return its own value, otherwise it will return its second operand.

Examples are as follows:

<?php
// 如果 $_GET[&#39;user&#39;] 不存在返回 &#39;nobody&#39;,否则返回 $_GET[&#39;user&#39;] 的值
$username = $_GET[&#39;user&#39;]??&#39;nobody&#39;;
// 类似的三元运算符
$username = isset($_GET[&#39;user&#39;])? $_GET[&#39;user&#39;]:&#39;nobody&#39;;
?>


##Spaceship operator (combined comparison operator)

The spaceship operator is used to compare two expressions. It returns

-1 when $a is greater than, equal to or less than $b respectively. , 0 or 1.

Examples are as follows:

<?php
// 整型
echo 1<=>1;// 0
echo 1<=>2;// -1
echo 2<=>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
?>


##Through

define() Define constant array##The example is as follows:

<?php
define(&#39;ANIMALS&#39;,[
    &#39;dog&#39;,
    &#39;cat&#39;,
    &#39;bird&#39;
]);
 
echo ANIMALS[1];// 输出 "cat"
?>


##Anonymous classes

now supports passing new class

To instantiate an anonymous class, the example is as follows:

<?php
interfaceLogger{
    publicfunction log(string $msg);
}
 
classApplication{
    private $logger;
 
    publicfunction getLogger():Logger{
         return $this->logger;
    }
 
    publicfunction setLogger(Logger $logger){
         $this->logger = $logger;
    }
}
 
$app =newApplication;
$app->setLogger(newclassimplementsLogger{
    publicfunction log(string $msg){
        echo $msg;
    }
});
 
var_dump($app->getLogger());
?>

以上实例会输出:

object(class@anonymous)#2(0){
}


Unicode codepoint 转译语法

这接受一个以16进制形式的 Unicodecodepoint,并打印出一个双引号或heredoc包围的 UTF-8 编码格式的字符串。可以接受任何有效的 codepoint,并且开头的 0 是可以省略的。

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

以上实例会输出:

ª
ª(same as before but with optional leading 0&#39;s)


Closure::call()

Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。

<?php
class A {private $x =1;}
 
// Pre PHP7 代码
$getXCB =function(){return $this->x;};
$getX = $getXCB->bindTo(new A,&#39;A&#39;);// intermediate closure
echo $getX();
 
// PHP 7+ 代码
$getX =function(){return $this->x;};
echo $getX->call(new A);

以上实例会输出:

1
1


unserialize()提供过滤

这个特性旨在提供更安全的方式解包不可靠的数据。它通过白名单的方式来防止潜在的代码注入。

<?php
 
// 转换对象为 __PHP_Incomplete_Class 对象
$data = unserialize($foo,["allowed_classes"=>false]);
 
// 转换对象为 __PHP_Incomplete_Class 对象,除了 MyClass 和 MyClass2
$data = unserialize($foo,["allowed_classes"=>["MyClass","MyClass2"]);
 
// 默认接受所有类
$data = unserialize($foo,["allowed_classes"=>true]);


IntlChar

新增加的 IntlChar 类旨在暴露出更多的 ICU 功能。这个类自身定义了许多静态方法用于操作多字符集的 unicode 字符。

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

以上实例会输出:

10ffff
COMMERCIAL AT
bool(true)

若要使用此类,请先安装Intl扩展


预期

预期是向后兼用并增强之前的 assert() 的方法。它使得在生产环境中启用断言为零成本,并且提供当断言失败时抛出特定异常的能力。

<?php
ini_set(&#39;assert.exception&#39;,1);
 
classCustomErrorextendsAssertionError{}
 
assert(false,newCustomError(&#39;Someerror message&#39;));
?>

以上实例会输出:

Fatalerror:Uncaught CustomError:Some error message


use 加强

从同一 namespace 导入的类、函数和常量现在可以通过单个 use 语句一次性导入了。

<?php
 
//  PHP 7 之前版本用法
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
 
usefunction some\namespace\fn_a;
usefunction some\namespace\fn_b;
usefunction some\namespace\fn_c;
 
useconst some\namespace\ConstA;
useconst some\namespace\ConstB;
useconst some\namespace\ConstC;
 
// PHP 7+ 用法
use some\namespace\{ClassA,ClassB,ClassCas C};
usefunction some\namespace\{fn_a, fn_b, fn_c};
useconst some\namespace\{ConstA,ConstB,ConstC};
?>



Generator 加强

增强了Generator的功能,这个可以实现很多先进的特性

<?php
<?php
 
function gen()
{
    yield1;
    yield2;
 
    yieldfrom gen2();
}
 
function gen2()
{
    yield3;
    yield4;
}
 
foreach(gen()as $val)
{
    echo $val, PHP_EOL;
}
 
?>

以上实例会输出:

1
2
3
4


整除

新增了整除函数 intp(),使用实例:

<?php
var_dump(intp(10,3));
?>

以上实例会输出:

int(3)

相关推荐:

php 5.4中新增加对session状态判断的功能

 

The above is the detailed content of New features added in PHP 7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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