PHP7.1 new features
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 the given type or null
#php5 function($a = null){ if($a===null) { return null; } return $a; } #php7+ function fun() :?string { return null; } function fun1(?$a) { var_dump($a); } fun1(null);//null fun1('1');//1
2. void type
return value Methods declared as void may simply omit the return statement. For void, NULL is not a legal return value.
function fun() :void { echo "hello world"; }
3. Class constant visibility
class Something { const PUBLIC_CONST_A = 1; public const PUBLIC_CONST_B = 2; protected const PROTECTED_CONST = 3; private const PRIVATE_CONST = 4; }
4. iterable pseudo class
This can be used in parameters or In the return value type, it represents an object that accepts an array or implements the Traversable interface.
function iterator(iterable $iter) { foreach ($iter as $val) { // } }
5. Multiple exception capture processing
One catch Statement blocks can now capture multiple exceptions through the pipe character (_|_). This is useful when you need to handle different exceptions from different classes at the same time
try { // some code } catch (FirstException | SecondException $e) { // handle first and second exceptions }
6. List supports key names
$data = [ ["id" => 1, "name" => 'Tom'], ["id" => 2, "name" => 'Fred'], ]; // list() style list("id" => $id1, "name" => $name1) = $data[0]; var_dump($id1);//1
7. String supports negative direction
$a= "hello"; $a[-2];//l
8. Convert callback to closure
Closure has added a new static method to quickly convert callable into a Closure object.
<?php class Test { public function exposeFunction() { return Closure::fromCallable([$this, 'privateFunction']); } private function privateFunction($param) { var_dump($param); } } $privFunc = (new Test)->exposeFunction(); $privFunc('some value');
9. http2 service push
Support for http2 server push has now been added to the CURL extension
Original link: https:// cloud.tencent.com/dev...
New features of PHP7.2
New object type
This new object type,object
, introduces any object type that can be used for contravariant parameter input and covariant return.
<?php function test(object $obj) : object { return new SqlQueue(); } test(new Stdclass());
Allow overriding of abstract methods
When an abstract class inherits from another abstract class, the inherited abstract class can override the abstraction of the inherited abstract class. method.
<?php abstract class A { abstract function test(string $s); } abstract class B extends A { abstract function test($s) : int; }
Use the Argon2 algorithm to generate password hashes
Argon2 has been added to the password hashing API (these functions start with password_), the following are the exposed constants:
PASSWORD_ARGON2I
PASSWORD_ARGON2_DEFAULT_MEMORY_COST
- ##PASSWORD_ARGON2_DEFAULT_TIME_COST
- PASSWORD_ARGON2_DEFAULT_THERADS
<?php use Foo\Bar\{ Foo, Bar, Baz, };PHP7.3 new features1 Release time06 Dec 2018Official website PHP7.3 new features2 Update Flexible
Heredoc and
Nowdoc syntax The
closing tag no longer needs to stand on its own line or be followed by a semicolon. At the same time, the closing tag can also use indentation. When indentation is used, each line of the doc content will skip the corresponding indentation. $data = ["元素", <<<STR Doc Content The new line STR, 42,]; var_dump($data); array(3) { [0]=> string(6) "元素" [1]=> string(25) "Doc Content The new line" [2]=> int(42) }In the above syntax, Heredoc appears as an array element, and the closing tag is not on a separate line and is indented. Note that in the defined string content, the indentation of both lines has been stripped. 3 Array destruction supports reference assignmentDemonstration:
$v = [10, 20]; [$a, &$b] = $v; $b += 10; var_dump($v, $a, $b); array(2) { [0]=> int(10) [1]=> &int(30) } int(10) int(30)When parsing $b, reference passing is used, at this time $b and $v[1] Elements maintain reference relationships. 4 The list structure supports reference resolution. Demonstration:
$v = [10, 20]; list($c, &$d) = $v; $d += 10; var_dump($v, $c, $d); array(2) { [0]=> int(10) [1]=> &int(30) } int(10) int(30)5 The instanceof operator supports literal syntax The first operand of instanceof supports literals, and the result of non-object literal detection is false .
var_dump("literal" instanceof stdClass); var_dump(42 instanceof stdClass); var_dump(new stdClass() instanceof stdClass); bool(false) bool(false) bool(true)6 Support trailing commas for parameters when calling When calling a function, a comma is allowed after the parameter list.
function methodName($p1, $p2) { // some statmenet var_dump($p1, $p2); } methodName(10, 20, ); int(10) int(20)When calling a function, adding a comma after the second (last) parameter is allowed. But the definition doesn't work. 7 BC mathematical function
bcscale()The function supports obtaining the scale used by the current BC function.
bcscale(3); var_dump(bcscale()); int(3)8 LDAP full supportLDAP: Lightweight Directory Access Protocol, lightweight directory access protocol is fully supported. 9 Multi-byte string function update
- Full-featured Case-Mapping and Case-Folding support
- Case-insensitive string operators use Case -Folding
- Support Unicode 11
- Long string support
- Named capture support
- log_limit
- log_buffering
- decorate_workers_output
14 废弃大小写不敏感的常量
大小写不敏感的常量声明现已被废弃。将 TRUE 作为第三个参数传递给 define() 会导致一个废弃警告。大小写不敏感的使用(在读取时使用一个与声明时不同的大小写方式)也已被废弃。
15 废弃在字符串中搜索非字符串内容
将一个非字符串内容传递给字符串搜索函数。 在将来所有待搜索的内容都将被视为字符串,而不是 ASCII 编码值。如果需要依赖这个特性,你应该 要么显示地进行类型转换(转为字符串),或者显示地调用 chr()。 以下是受到影响的方法:
16 新常量
新常量
原文链接:https://zhuanlan.zhihu.com/p/...
PHP7.4新特性
1、预加载
预加载功能是指在服务启动时,未运行任何应用程序代码之前,将一组PHP文件加载到内存中,甚至可以对框架进行预加载,以提高性能。如果对预加载代码进行修改,需要重启服务。
预加载相比opcache:opcache虽然解决了重复编译问题,但opcache本身也有开销。引用Dmitry Stogov大佬的话:
Not only. The idea is to completely eliminate compilation and opcache overhead (copying from SHM to process memory and insertions into function/class tables on each request). Using this technique, we might write standard functions and classes in PHP (similar to systemlib.php in HHVM).
预加载是完全消除编译和opcache所带来的开销(从共享内存复制到进程内存,并在每个请求上插入到function/class表中),使用这种技术可以在PHP中编写标准函数和类(类似于HHVM中的systemlib.php)
想想看,其实预加载主要是提升像php-fpm这种架构形式的性能,并且会占用更多的内存资源。Benjamin Morel对预加载进行了测试。
https://github.com/composer/composer/issues/7777#issuecomment-440268416
使用方法:
通过修改php.ini中的opcache.preload
来选择预加载程序。使用方法如下:
php.ini
[opcache] zend_extension=opcache.so opcache.enable=1 opcache.enable_cli=1 opcache.preload=preload.php
preload.php
<?php function preload() { echo 'preload'; } opcache_compile_file('hello.php');
hello.php
<?php function hello() { echo 'hello'; }
test.php
<?php hello(); echo ' '; preload(); echo PHP_EOL;
运行
~$ php test.php hello preload
2、FFI
有时间我们再聊,先占上位置。
3、类属性的类型支持
php版本<7.4:
<?php class User { /** @var int $id */ private $id; /** @var string $name */ public $name; }
php版本>=7.4:
<?php class User { private int $id; public string $name; }
一个完整的示例:
<?php class Example { // 支持除了“void”和“callable”之外的所有类型 public int $scalarType; protected ClassName $classType; private ?ClassName $nullableClassType; // 在静态属性中也是合法的 public static iterable $staticProp; // 也可以与“var”一起使用 var bool $flag; // 也可以使用默认值 public string $str = "foo"; public ?string $nullableStr = null; // 在一次声明多个属性的情况下,类型会作用于各属性。 public float $x, $y; // 相当于这样: public float $x; public float $y; }
以下是支持的所有类型:
bool, int, float, string, array, object iterable self, parent class interface // 任何 类名、接口名 ?type // 其中“type”可以是以上任意一种类型
4、NULL合并赋值运算符
写法:$a ??= 1 。其实就是 $a = $a ?? 1 的语法糖。
例子:
<?php $arr['a'] ??= 'a'; /*等同于*/ $arr['a'] = $arr['a'] ?? 'a'; $b ??= 'b'; /*等同于*/ $b = $b ?? 'b';
5、弃用WDDX扩展
我相信大多数人和我一样并不了解wddx,wddx是一个很“古老”的数据格式,基于xml(emmm,可能我理解的不是很对,大概其就是这个意思吧)。现在都在用json,所以弃用了也罢。有兴趣的童鞋可以看一下这篇文章。
https://blog.csdn.net/guoguo1980/article/details/2436342
6、简化匿名函数
此特性就是一个语法糖,相信你在别的语言中也见到过,下面是一些例子:
<?php $adder = fn($x, $y) => $x + $y; // 等同于 $adder = function ($x, $y) { return $x + $y; }; /*******************************/ $y = 1; $fn1 = function ($x) use ($y) { return $x + $y; }; // 等同于 $fn2 = fn($x) => $x + $y; // 新的写法省去了 use, 变得更加简洁
更多用法:
<?php fn(array $x) => $x; // 参数类型声明 fn(): int => $x; // 返回类型声明 fn($x = 42) => $x; // 参数默认值 fn(&$x) => $x; // 引用传递 fn&($x) => $x; // 引用返回 fn($x, ...$rest) => $rest; // 变长参数
其实我个人不是很赞同php引入那么多语法糖,这使得php的语法变得越来越复杂,关于此rfc的投票,鸟哥选择了反对,包括韩天峰大佬也对此特别反对,php应该回归初心——简单高效。
7、新增mb_str_split函数
mb_str_split是mbstring扩展中新增的一个函数,通过函数名就可以猜到,它是str_split函数的“增强版(多字节处理)”,它的作用和str_split一样,都是将字符串拆分成数组,只是增加了第三个参数,用于设置字符编码。
说明:
mb_str_split ( string $string [, int $split_length = 1, string $encoding = mb_internal_encoding() ] ) : array
例子:
<?php print_r(mb_str_split("PHP是世界上最好的语言", 3)); // Array // ( // [0] => PHP // [1] => 是世界 // [2] => 上最好 // [3] => 的语言 // ) // 也可以指定编码 print_r(mb_str_split("PHP是世界上最好的语言", 3, "GB2312"));
8、始终可用的Hash扩展
从PHP7.4开始,Hash扩展是PHP核心扩展,无法通过--disable-hash禁用,因此它始终可用。