博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP 7.4简介:性能,功能,弃用
阅读量:2508 次
发布时间:2019-05-11

本文共 14840 字,大约阅读时间需要 49 分钟。

PHP evolves continuously and they just released their latest PHP 7.4 update. Performance and speed keep advancing, as we have already been proved in the past PHP 7 releases. Preloading is one of the most thrilling new updates. It quickens script execution and makes code cleaner and faster due to the simplified common lines of code.

PHP不断发展,他们刚刚发布了最新PHP 7.4更新。 正如我们在过去PHP 7版本中所证明的那样,性能和速度在不断提高。 预加载是最令人激动的新更新之一。 由于简化了常见的代码行,因此可以加快脚本执行速度,并使代码更清洁,更快。

PHP is an important element in the world wide web and is used in of all websites. Well-known websites like Facebook, Wikipedia, WordPress and much more are using PHP. We can see a double speed increase when looking at WordPress sites running PHP and comparing PHP 5 and 7. While using the latest PHP version out there — WordPress powered websites gain the most.

PHP是万维网上的重要元素,并且在的网站中使用。 诸如Facebook,Wikipedia,WordPress等知名网站都在使用PHP。 当查看运行PHP的WordPress网站并比较PHP 5和7时,我们可以看到速度提高了两倍。在使用最新PHP版本的情况下– WordPress驱动的网站获得了最大的收益。

Currently, there are around 40 mln. websites using PHP. This graph illustrates the performance of the websites that use PHP actively. Overall, PHP 7.4 is looking quite good over PHP 7.3 with better performance on top of introducing the FFI capabilities, the preload feature, and other improvements. The following graph compares the overall results on 7.4 and older PHP versions.

目前,大约有4000万。 使用PHP的网站。 该图说明了积极使用PHP的网站的性能。 总体而言,除了引入FFI功能,预加载功能和其他改进之外,PHP 7.4与PHP 7.3相比看上去还不错。 下图比较了7.4和更早版本PHP上的总体结果。

PHP 7.4的新增功能? (What’s New in PHP 7.4?)

PHP7 has been releasing constant yearly updates since 2016. Various new features, ability to write cleaner code to make the language more trustworthy and convenient if you run it on your website. Let’s catch a glimpse of some modifications that were made with the PHP 7.4 release. You can find the full list in their .

自2016年以来,PHP7每年都在不断发布更新。各种新功能,编写更简洁的代码的能力使该语言在您的网站上运行时更加值得信赖和方便。 让我们看一下PHP 7.4版本所做的一些修改。 您可以在他们的找到完整列表。

预装 (Preloading)

Preloading is when you’re able to load frameworks and libraries into the OPCache. It’s a truly convenient feature since files have to be loaded and linked on every request while using a framework or libraries. Loading the PHP files and storing it in memory at startup to have them ready for any coming requests? Preloading does that!

预加载是指您能够将框架和库加载到OPCache中。 这是一个真正方便的功能,因为在使用框架或库时,必须根据每个请求加载和链接文件。 加载PHP文件并在启动时将其存储在内存中,以使其准备好应付任何即将到来的请求? 预加载可以做到这一点!

Preloading is controlled by a single new php.ini directive: opcache.preload. Using this directive we can specify a single PHP file — which will perform the preloading task. Once loaded, this file is then fully executed — and may preload other files, either by including them or by using the opcache_compile_file() function.

预加载由一个新的php.ini指令控制: opcache.preload 。 使用此指令,我们可以指定一个PHP文件-将执行预加载任务。 加载后,此文件将完全执行-可以通过包含其他文件或使用opcache_compile_file()函数来预加载其他文件。

As I’ve already mentioned, preloaded files will stay cached in opcache memory indefinitely. Modification of their corresponding source files won’t have any effect without another server restart.

正如我已经提到的,预加载的文件将无限期地保留在opcache内存中。 不重新启动另一台服务器,对其相应源文件的修改将无效。

Therefore, in case you should want to use these preloaded files again — it will be accessible for any forthcoming requests.

因此,以防万一您想再次使用这些预加载的文件-即将出现的任何请求都可以使用它。

数组表达式中的扩散运算符 (Spread Operator in Array Expressions)

PHP started to maintain argument unpacking (spread operator), way back on PHP 5.6 release. Now, with 7.4, we can use this feature with an array expression. The syntax for unpacking arrays and Traversables into argument lists is called argument unpacking. And to make that happen, you only need to prepend it by 3 dots (…).

PHP开始维护参数解压缩(扩展运算符),早在PHP 5.6发行版中。 现在,在7.4中,我们可以将此功能与数组表达式一起使用。 将数组和Traversables解压缩为参数列表的语法称为参数解压缩。 为了做到这一点,您只需在其前面加上3个点(...)。

Take a look at this instance:

看一下这个实例:

$tropicalfruits = ['banana', 'orange'];$fruits = ['apple', 'pear', ...$tropicalfruits, 'plum'];// [‘apple’, ‘pear’, ‘banana’, ‘orange’, ‘plum’];

Now it’s possible to expand an array from anywhere in another array, by using the Spread Operator syntax.

现在,可以使用Spread Operator语法从另一个数组中的任何位置扩展数组。

A longer example:

一个更长的例子:

$num1 = [1, 2, 3];$num2 = [...$num1]; // [1, 2, 3]$num3 = [0, ...$num1]; // [0, 1, 2, 3]$num4 = array(...$num1, ...$num2, 111); // [1, 2, 3, 1, 2, 3, 111]$num5 = [...$num1, ...$num1]; // [1, 2, 3, 1, 2, 3]

In addition, you can use it in a function. Like in this example:

function getNum() { return ['x', 'y'];}$num6 = [...getNum(), 'z']; // ['x', 'y', 'z'] $num7 = [...new NumIterator(['x', 'y', 'z'])]; // ['x', 'y', 'z'] function arrGen() { for($i = 11; $i < 15; $i++) { yield $i; }}$num8 = [...arrGen()]; // [11, 12, 13, 14]

Now you’re also able to unpack arrays and generators that are returned by a function straight into a new array:

现在,您还可以将函数返回的数组和生成器解压缩到新数组中:

function getFruits(){return ['apple', 'orange', 'banana'];}$num1 = [...getFruits(), 'plum', 'grapefruit', 'watermelon'];

With PHP 7.4 it would return this:

使用PHP 7.4它将返回以下内容:

array(6) {[0]=>string(3) "apple"[1]=>string(3) "orange"[2]=>string(8) "banana"[3]=>string(4) "plum"[4]=>string(5) "grapefruit"[5]=>string(7) "watermelon"}

Using this array expression, spread operators should have way better performance over the 7.3 array_merge. This is due to the spread operator being a language structure, while array_merge is a function. Another reason is that the spread operator supports the object's implementation of traversable when array_merge only supports arrays.

使用此数组表达式,散布运算符应该比7.3 array_merge具有更好的性能。 这是因为传播运算符是一种语言结构,而array_merge是一个函数。 另一个原因是,当array_merge仅支持数组时,散布运算符支持对象的可遍历实现。

Additional amazing and really convenient feature that came with 7.4 is the removal of the array_merge indexed arrays. This is because string keys are not supported. Index shift no more!

7.4附带的另一个令人惊奇且真正方便的功能是删除了array_merge索引数组。 这是因为不支持字符串键。 索引移位不再了!

$array = [‘dog, ‘cat’];$array[2] = ‘cat’;$array[1] = ‘giraffe’; //shiftingvar_dump($array);// printsarray(3) {[0]=>string(6) "dog"[1]=>string(5) "giraffe"[2]=>string(6) "cat"

Another PHP 7.4 advantage over the older versions is the . Difference between generator function and normal function is that, a generator function yields as many values as it needs to instead of returning a value. So, any function containing is a generator function:

与旧版本相比,PHP 7.4的另一个优点是 。 生成器函数和普通函数之间的区别在于,生成器函数会产生所需数量的值,而不是返回值。 因此,任何包含的函数都是一个生成器函数:

function generator() {for ($i = 3; $i <= 5; $i++) {yield $i;}}$num1 = [0, 1, 2, ...generator()];

参考文献薄弱 (Weak References)

PHP 7.4 has a WeakReference class which lets you retain a reference to an object which does not prevent the object from being destroyed. It is useful for implementing cache-like structures. Be aware to not mistake WeakReference with the WeakRef class or Weakref extension.

PHP 7.4具有WeakReference类,该类使您可以保留对对象的引用,而该引用不会阻止对象被破坏。 这对于实现类似缓存的结构很有用。 请注意不要将WeakReferenceWeakRef类或Weakref扩展相混淆

WeakReference {/* Methods */public __construct ( void )public static create ( object $referent ) : WeakReferencepublic get ( void ) : ?object}

协变参数和协变返回 (Contravariant Parameters and Covariant Returns)

At the moment, PHP mostly uses invariant parameter types and return types. This implies that the subtype parameter or return type must also be type X if a method has parameter or return type of X.

目前,PHP主要使用不变的参数类型和返回类型。 这意味着,如果方法的参数或返回类型为X ,则子类型参数或返回类型也必须为X类型。

With PHP 7.4 it offers to enable contravariant (reversing the order) and covariant (ordered from specific to generic) on parameter and return types.

使用PHP 7.4,它可以在参数和返回类型上启用逆变 (逆序)和协变 (从特定顺序到泛型)。

Let’s take a look at both:

让我们看一下两者:

Covariant return type:

协变返回类型:

interface Factory {function make(): object;}class UserFactory implements Factory {function make(): User;}

Contravariant parameter type:

变量参数类型:

interface Concatable {function concat(Iterator $input);}class Collection implements Concatable {// accepts all iterables, not just Iteratorfunction concat(iterable $input) {/* . . . */}}

键入属性2.0 (Typed Properties 2.0)

Type hints have been an available feature since PHP 5. It allows you to specify the type of variable that is intended to be passed to a function or class.

自PHP 5起,类型提示已成为可用功能。它允许您指定要传递给函数或类的变量的类型。

In the PHP 7.2 migrations, the supplement of the object data type gave hope that more would be available in the future.

在PHP 7.2迁移中,对象数据类型的补充使人们希望将来会有更多可用。

In PHP 7.4, it is possible to support the type list below:

在PHP 7.4中,可以支持以下类型列表:

bool, int, float, string, array, object, iterable, self, parentany class or interface name?type // where "type" may be any of the above

Parent type can be used in classes and doesn’t need to have a parent constant with the parameter and return type.

类型可以在类中使用,不需要带有参数和返回类型的父常量。

Besides, callable and void are not supported. Callable was removed because its behavior was context-dependent; void, because it was not useful and had unclear semantics.

此外,不支持callablevoidCallable被删除,因为它的行为取决于上下文。 void ,因为它没有用并且语义不明确。

Take a look at the examples below.

看下面的例子。

A PHP 7.3 class:

一个PHP 7.3类:

class User {    /** @var int $id */    private $id;    /** @var string $name */    private $name;    public function __construct(int $id, string $name) {        $this->id = $id;        $this->name = $name;    }    public function getId(): int {        return $this->id;    }    public function setId(int $id): void {        $this->id = $id;    }    public function getName(): string {        return $this->name;    }    public function setName(string $name): void {        $this->name = $name;    }}

In PHP 7.4 classes are simple as that:

在PHP 7.4中,类很简单:

class User {    public int $id;    public string $name;    public function __construct(int $id, string $name) {        $this->id = $id;        $this->name = $name;    }}

PHP 7.4 supported types:

PHP 7.4支持的类型:

class Example {      public int $scalarType;    protected ClassName $classType;    private ?ClassName $nullableClassType;     // Types are also legal on static properties    public static iterable $staticProp;     // Types can also be used with the "var" notation    var bool $flag;     // Typed properties may have default values (more below)    public string $str = "foo";    public ?string $nullableStr = null;     // The type applies to all properties in one declaration    public float $x, $y;    // equivalent to:    public float $x;    public float $y;}

箭头功能2.0 (Arrow Functions 2.0)

Arrow functions in PHP often are redundant and prolonged, even in case of performing simple actions. This is partly because of a great deal of syntactic boilerplate, and partly because of the necessity to imply used variables manually.

即使在执行简单操作的情况下,PHP中的箭头函数也经常是多余的并且被延长。 这部分是由于大量的语法模板,部分是由于必须手动暗示使用的变量。

This makes a code with a minor functionality complex and difficult to read.

这使得具有次要功能的代码变得复杂且难以阅读。

This would be an anonymous function in PHP 7.3:

这将是PHP 7.3中的匿名函数:

function array_values_from_keys($arr, $keys) {    return array_map(function ($x) use ($arr) { return $arr[$x]; }, $keys);}

And this is an easy to read arrow function in PHP 7.4:

这是PHP 7.4中易于阅读的箭头功能:

function array_values_from_keys($arr, $keys) {    return array_map(fn($x) => $arr[$x], $keys);}

Hence, that arrow functions are this straightforward:

因此,箭头功能非常简单:

fn(parameter_list) => expr

There you can see two functions $fn1 and $fn2. Code looks different but functions pass identical result.

在那里,您可以看到两个函数$ fn1$ fn2 。 代码看起来不同,但是函数传递相同的结果。

$c = 1;$fn1 = fn($a) => $a + $c;  $fn2 = function ($a) use ($c){    return $a + $c;};

This will also surely work with nested arrow functions:

当然也可以使用嵌套箭头功能:

$c = 1;$fn = fn($a) => fn($b) => $a * $b + $c;

This is something out of 7.3 capabilities. The parent function acquires $c while the child function also acquires $c from the parent function. In PHP 7.4, the external range can become accessible in the child function.

这是7.3功能之外的功能。 父函数获取$ c,而子函数也从父函数获取$ c。 在PHP 7.4中,可以在子函数中访问外部范围。

Arrow functions syntax let us use variadics, default values, parameter and return types, as well as by-reference passing and returning, while letting us keep a clear, understandable appearance.

箭头函数语法使我们可以使用变量,默认值,参数和返回类型,以及按引用传递和返回,同时使我们保持清晰易懂的外观。

fn(array $a) => $a;fn(): int => $a;fn($a = 42) => $a;fn(&$a) => $a;fn&($a) => $a;fn($a, ...$rest) => $rest;

Also it’s worth indicating that arrow functions have the lowest priority:

同样值得指出的是,箭头功能的优先级最低:

fn($a) => $a + $b// isfn($a) => ($a + $b)// not(fn($a) => $a) + $b

弃用 (Deprecations)

As for now the precedence of `.`, `+` and `-` operators are equal. Any combination of these operators will be solved from left-to-right.

目前,`。、、 +和-的优先级是相等的。 这些运算符的任意组合将从左到右求解。

Check out this 7.3 code below:

在下面查看此7.3代码:

echo "sum: " . $x + $y;// would be evaluated left-to-rightecho ("sum: " . $x) + $y;// or like this

With PHP 7.4 the additions and subtractions would always be performed before the string, due to `+` and `-` taking priority over `.`:

在PHP 7.4中,由于`+`和`-`优先于`.`,因此总是在字符串之前执行加减法:

echo "sum: " . $x + $y;// would be performed as if the code were as below.echo "sum :" . ($x + $y);

This two-step suggestion claims to be less fallible and more instinctive.

这个两步走的建议声称不那么容易犯错,更具有本能。

左缔合三元运算符 (Left-Associative Ternary Operator)

Contrary to most other languages, the ternary operator in PHP is left-associative rather than right-associative. PHP 7.4 intention is that instead of the use of left-associativity — start using the parentheses. So it wouldn’t be unusual and puzzling for programmers who switch between different languages.

与大多数其他语言相反,PHP中的三元运算符是左关联的,而不是右关联的。 PHP 7.4的意图是代替使用左关联性-开始使用括号。 因此,对于在不同语言之间进行切换的程序员而言,这并不罕见且令人困惑。

Let’s see the example below:

让我们看下面的例子:

return $a == 1 ? 'one' 	: $a == 2 ? 'two' 	: $a == 3 ? 'three' 	: $a == 4 ? 'four'           	: 'other';

In the majority of other languages it would be read as:

在大多数其他语言中,其含义如下:

return $a == 1 ? 'one' 	: ($a == 2 ? 'two' 	: ($a == 3 ? 'three' 	: ($a == 4 ? 'four'           	: 'other')))

While in PHP, it is instead read as:

在PHP中,它改为:

return ((($a == 1 ? 'one' 	: $a == 2) ? 'two' 	: $a == 3) ? 'three' 	: $a == 4) ? 'four'           	: 'other';

Due to the fact that it’s usually not what was planned, this could cause errors.

由于通常不是计划的事实,因此可能会导致错误。

结论 (Conclusion)

PHP 7.4 elevates new handy features and conveniences for every PHP programmer out there.

PHP 7.4为每个PHP程序员带来了新的便捷功能和便利。

WordPress websites and their users will definitely benefit from these improvements. Reduced memory usage and rapid execution times are just a few of many advancements while using PHP 7.4 in contrast with previous releases.

WordPress网站及其用户一定会从这些改进中受益。 与以前的版本相比,使用PHP 7.4时,减少内存使用量和缩短执行时间只是许多进步中的一小部分。

PHP 7.4 will certainly enhance both the speed and quality of your working process with the extension of arrow merging functions, first-class property type declarations and type hinting, and insanely better speed.

PHP 7.4肯定会通过扩展箭头合并功能,一流的属性类型声明和类型提示来提高工作过程的速度和质量,并以惊人的速度提高。

翻译自:

转载地址:http://kzdwd.baihongyu.com/

你可能感兴趣的文章
C# 调用WebService的3种方式 :直接调用、根据wsdl生成webservice的.cs文件及生成dll调用、动态调用...
查看>>
大数据初入门
查看>>
Java学习笔记-类型初始化
查看>>
设计模式原则之单一职责原则
查看>>
Android:日常学习笔记(10)———使用LitePal操作数据库
查看>>
鱼那么信任水,水却煮了鱼
查看>>
HTML5 Canvas ( 文字的度量 ) measureText
查看>>
Http和Socket连接区别
查看>>
Arrays基本使用
查看>>
受限玻尔兹曼基
查看>>
Angular2,Springboot,Zuul,Shiro跨域CORS请求踩坑实录
查看>>
(转载)iptables 转发oracle端口
查看>>
如何删除docker images/containers
查看>>
C语言中操作符的优先级大全
查看>>
大公司还是创业公司,你怎么选择?
查看>>
图论+dp poj 1112 Team Them Up!
查看>>
UVa 10131: Is Bigger Smarter?
查看>>
POJ - 2236-Wireless Network (并查集)
查看>>
android中TextView的阴影设置
查看>>
谈谈Java中的ThreadLocal
查看>>