PHP 5.5的新功能

PHP 5.5 was recently released, introducing several exciting new features to the language. In this article, we’ll go through some of the most interesting additions and discuss the benefits they provide to developers.

最近发布了PHP 5.5,为该语言引入了一些令人兴奋的新功能。 在本文中,我们将介绍一些最有趣的功能,并讨论它们为开发人员提供的好处。

发电机 (Generators)

Generators are one of the most eagerly anticipated new features. They provide a way to handle iteration without having to write a class that implements the Iterator interface. Making a class conform to the Iterator interface requires a substantial amount of boilerplate code, so being able to avoid this by using generators can significantly reduce the size and complexity of code that developers must write.

生成器是最受期待的新功能之一。 它们提供了一种处理迭代的方法,而无需编写实现Iterator接口的类 。 使一个类符合Iterator接口需要大量的样板代码,因此,通过使用生成器来避免这种情况,可以大大减少开发人员必须编写的代码的大小和复杂性。

Generators derive their functionality from the new yield keyword. A generator looks very similar to a normal function, but instead of returning a single value, a generator may yield any number of values.

生成器从新的yield关键字派生其功能。 生成器看起来与普通函数非常相似,但是生成器可以返回任意数量的值,而不是返回单个值。

To properly illustrate the power of generators, an example is needed. Consider PHP’s range() function, which returns an array of the values between the $start and $end arguments. We can use range() as follows:

为了正确地说明发电机的功率,需要一个例子。 考虑PHP的range()函数,该函数返回$start$end参数之间的值的数组。 我们可以如下使用range()

<?php
foreach (range(0, 1000000) as $number) {
    echo $number;
}

The problem in this example is that the array returned by range() will occupy a lot of memory (over 100mb according to the PHP manual). While the above code is a trivial demonstration, there are plenty of real-world situations where large arrays of data are constructed, often taking a long time to build and occupying a lot of memory.

此示例中的问题是range()返回的数组将占用大量内存(根据PHP手册,超过100mb)。 尽管上面的代码是一个简单的演示,但在现实世界中,有很多情况是要构建大量数据,通常需要很长时间才能构建并占用大量内存。

With the introduction of generators, it’s now easy to tackle this problem without the inconvenience of having to write an Iterator class. Generators do not construct a large array, but rather return a single element at a time as they are iterated. Consider this modification to the above code, now using a generator to produce the range of values:

随着生成器的引入,现在可以轻松解决此问题,而不必编写Iterator类。 生成器不构造大型数组,而是在迭代时一次返回单个元素。 考虑对上面代码的修改,现在使用生成器来生成值的范围:

<?php
// define a simple range generator
function generateRange($start, $end, $step = 1) {
    for ($i = $start; $i < $end; $i += $step) {
        // yield one result at a time
        yield $i;
    }
}

foreach (generateRange(0, 1000000) as $number) {
    echo $number;
}

This code produces exactly the same result as the first example, but without producing a large array to store all the values. According to the manual, this reduces the memory footprint to less than a single kilobyte – a huge saving compared with the original example.

此代码产生的结果与第一个示例完全相同,但是没有产生大数组来存储所有值。 根据该手册,这可以将内存占用空间减少到不到一千字节-与原始示例相比节省了很多。

密码哈希 (Password Hashing)

The new password hashing API is one of the most important and useful features added in PHP 5.5. In the past, developers have had to rely on the somewhat confusing crypt() function, which is poorly documented in the PHP manual. The introduction of a simplified set of functions to handle password hashing will make it much easier for developers to understand and implement secure password hashing for their sites.

新的密码哈希API是PHP 5.5中添加的最重要和最有用的功能之一。 过去,开发人员不得不依靠有些令人困惑的crypt()函数,该函数在PHP手册中很少记录。 引入一组简化的函数来处理密码哈希处理将使开发人员更容易理解和实现其站点的安全密码哈希处理。

The new API introduces two new functions, password_hash() and password_verify(). Calling password_hash($password, PASSWORD_DEFAULT) will return a strong hash using bcrypt, with salting handled automatically. Verifying the password later is as easy as checking the result of password_verify($password, $hash).

新的API引入了两个新功能, password_hash()password_verify() 。 调用password_hash($password, PASSWORD_DEFAULT)将使用bcrypt返回强哈希,并自动处理盐分 。 稍后验证密码就像检查password_verify($password, $hash)的结果一样容易。

The API uses bcrypt by default, but in the future new algorithms may be introduced to provide even more secure methods of hashing. Developers can specify their own bcrypt work factor to adjust the strength of the hashes produced, and can also use their own salts instead of the automatic salt generation (although the manual discourages this).

该API默认使用bcrypt,但将来可能会引入新算法以提供更安全的哈希方法。 开发人员可以指定自己的bcrypt工作系数来调整生成的哈希值的强度,还可以使用自己的盐代替自动生成盐(尽管这样做会不利于人工操作)。

最后 (finally)

PHP 5.5 adds support for the finally keyword, a much-requested feature found in many other languages with exception handling. finally allows developers to specify code to be run at the end of try and catch blocks, regardless of whether an exception was thrown or not, before the normal execution flow resumes.

PHP 5.5添加了对finally关键字的支持,这是在许多其他语言中具有异常处理功能的功能,是人们所要求的。 finally ,开发人员可以在继续正常执行流程之前,在trycatch块的末尾指定要运行的代码,而不管是否引发了异常。

Without the finally keyword, developers were sometimes be forced to repeat code within both the try and catch blocks to handle cleanup tasks. For example, in the following example the call to releaseResource() must be made in two places:

没有finally关键字,有时会迫使开发人员在trycatch块中重复代码以处理清理任务。 例如,在下面的示例中,必须在两个位置调用releaseResource()

<?php
function doSomething() {
    $resource = createResource();
    try {
        $result = useResource($resource);
    }
    catch (Exception $e) {
        releaseResource($resource);
        log($e->getMessage());
        throw $e;
    }
    releaseResource($resource);
    return $result;
}

With the addition of finally, we can eliminate the duplicate code:

通过添加finally ,我们可以消除重复的代码:

<?php
function doSomething() {
    $resource = createResource();
    try {
        $result = useResource($resource);
        return $result;
    }
    catch (Exception $e) {
        log($e->getMessage());
        throw $e;
    }
    finally {
        releaseResource($resource);
    }
}

In the modified version, we call the cleanup function releaseResource() in the finally block where we know it will always be called. Note that even though the try block returns a value, the finally block will still be called before the return statement is executed and normal execution continues.

在修改后的版本中,我们在finally块中调用清理函数releaseResource()在该块中,它将始终被调用。 请注意,即使try块返回了一个值,在执行return语句和继续正常执行之前, finally块仍将被调用。

数组和字符串文字解引用 (Array and String Literal Dereferencing)

Array and string literals can now be dereferenced using array access syntax:

现在可以使用数组访问语法取消引用数组和字符串文字:

<?php
// array dereferencing - returns 3
echo [1, 3, 5, 7][1];

// string dereferencing - returns "l"
echo "hello"[3];

This feature was added primarily to improve the consistency of the language, and probably won’t revolutionize the way we write PHP. However, there are some interesting applications to consider, such as the following:

添加此功能主要是为了提高语言的一致性,并且可能不会改变我们编写PHP的方式。 但是,有一些有趣的应用程序需要考虑,例如:

<?php
$randomChar = "abcdefg0123456789"[mt_rand(0, 16)];

在函数调用和表达式中使用empty() (Using empty() with Function Calls and Expressions)

The empty() construct can now be used with function calls and other expressions. For example, empty($object->getProperty()) is valid code in PHP 5.5. This makes it possible to use empty() on the return value of functions without capturing the value in a variable first.

现在可以将empty()构造与函数调用和其他表达式一起使用。 例如, empty($object->getProperty())是PHP 5.5中的有效代码。 这样就可以在函数的返回值上使用empty() ,而无需先捕获变量中的值。

类名解析 (Class Name Resolution)

Since the introduction of namespaces in PHP 5.3, it has become common practice to use extensive namespacing to organize classes in PHP projects. However, until now it has been difficult to retrieve a fully-qualified class name as a string. Consider the following code:

自从PHP 5.3中引入名称空间以来,使用广泛的命名空间来组织PHP项目中的类已成为一种惯例。 但是,到目前为止,很难将完全合格的类名检索为字符串。 考虑以下代码:

<?php
use NamespacedClassFoo;

$reflection = new ReflectionClass("Foo");

This will fail as PHP will attempt to use the global Foo class instead of the namespaced class. In PHP 5.5, it is now possible to retrieve the full namespaced class name as a string using the class keyword:

这将失败,因为PHP将尝试使用全局Foo类而不是命名空间类。 在PHP 5.5中,现在可以使用class关键字以字符串的形式检索完整的命名空间类名称:

<?php
use NamespacedClassFoo;

$reflection = new ReflectionClass(Foo::class);

This will now work as intended, as Foo:class will resolve to Namespaced\Class\Foo.

现在这将按预期工作,因为Foo:class将解析为Namespaced\Class\Foo

更改为foreach (Changes to foreach)

The list() construct in PHP allows the values of an array to be easily assigned to variables. For example:

PHP中的list()构造允许将数组的值轻松分配给变量。 例如:

<?php
$values = ["sea", "blue"];

list($object, $description) = $values;

// returns "The sea is blue"
echo "The $object is $description";

It’s now possible to use list() with multidimensional arrays within foreach loops. For example:

现在可以将list()foreach循环内的多维数组一起使用。 例如:

<?php
$data = [
    ["sea", "blue"],
    ["grass", "green"]
];

foreach ($data as list($object, $description)) {
    echo "The $object is $descriptionn";
}

/* Outputs:
The sea is blue
The grass is green
*/

This is a powerful new feature that has the potential to make iterating through nested arrays much easier and cleaner.

这是一项强大的新功能,有可能使嵌套数组的迭代变得更加轻松和整洁。

foreach loops can now also handle non-scalar values as iterator keys, which means that element keys may have values that are not strings or integers.

foreach循环现在还可以将非标量值作为迭代器键来处理,这意味着元素键的值可能不是字符串或整数。

结论 (Conclusion)

PHP 5.5 offers many improvements to facilitate PHP development. In addition to new features, a long list of bugs have been resolved in this release (see the changelog for details), and various optimizations and enhancements have been made to improve performance and stability.

PHP 5.5提供了许多改进来促进PHP开发。 除了新功能之外,此版本中还解决了许多错误(有关详细信息,请参见更新日志),并且进行了各种优化和增强以提高性能和稳定性。

Will you be upgrading to PHP 5.5? Let us know in the comments.

您将升级到PHP 5.5吗? 让我们在评论中知道。

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/whats-new-in-php-5-5/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值