設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 890|回復: 0
打印 上一主題 下一主題

New features in PHP 7: a quick overview

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2016-1-17 13:53:18 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
Have a look at the video, it highlights a couple of features I like in PHP 7. Here’s the list of stuff I cover:
Scalar type hints
Type hints
have been available in PHP for while now. Unfortunately they were restricted to classes, arrays and callables.
As of PHP 7, the scalar types (integers, floating point numbers, booleans and strings) can also be used as type hints.
  1. <?php
  2. /**
  3. * Scalar type declarations
  4. */
  5.   
  6. //declare(strict_types=1);
  7. function add(int $a, int $b) {
  8.      return $a + $b;
  9. }
  10.   
  11. var_dump(add(1,2));
  12. var_dump(add("1","2"));
複製代碼

I’m happy with this feature, because it allows developers to ensure a better input consistency of a function/method interface.
By default “coercive mode” is enabled.
This restricts PHP from throwing a type error when the types don’t exactly match, but when a conversion is still possible.
If you enable “strict mode” (by uncommenting line 6), a type error is thrown when the signatures don’t match.
Return type declarations
Whereas type hints ensure input consistency, return type declarations ensure output consistency.
We use a colon before the opening curly brace of a function to hint the return type.
  1. <?php
  2. /**
  3. * Return type declarations
  4. */
  5.   
  6. //declare(strict_types=1);
  7. function add(int $a, int $b): int{
  8.      return (string)($a + $b);
  9. }
  10.   
  11. var_dump(add(1,2));
複製代碼

The same strictness rules apply as with the type hints:
if “strict mode” is disabled, return values that can be converted to the preferred type are allowed. If you enable “strict mode” this code will throw a type error.
Anonymous classes
Anonymous classes are useful for simple one-off objects. With anonymous classes you can define a class and instantiate an object inline.
  1. <?php
  2. /**
  3. * Anonymous classes
  4. */
  5.   
  6. $foo = new class {
  7.      public function foo() {
  8.          return "bar";
  9.      }
  10. };
  11.   
  12. var_dump($foo,$foo->foo());
複製代碼

The Closure::call() method
Closures are anonymous functions that are declared inline and assigned to a variable.
It can be used as a callback for later execution.
In PHP 5 it was already possible to bind an object to the scope of the closure as if it was a method.
In PHP 7 the “call” method has been introduced to simplify the process.
  1. <?php
  2. /**
  3. * Closure::call()
  4. */
  5.   
  6. class Foo
  7. {
  8.      private $foo = 'bar';
  9. }
  10.   
  11. $getFooCallback = function() {
  12.      return $this->foo;
  13. };
  14.   
  15. //PHP5 style
  16. $binding = $getFooCallback->bindTo(new Foo,'Foo');
  17. echo $binding().PHP_EOL;
  18.   
  19. //PHP7 style
  20. echo $getFooCallback->call(new Foo).PHP_EOL;
複製代碼
Generator delegation
Generators are cool, but sometimes hard to explain. Ironically using them is surprisingly simple.
It’s all about the “yield” keyword. By using “yield”, a generator is returned with the value that is yielded.
A generator implements an iterator which makes it easy to use in while or for loops.
In PHP 7 generator delegation was introduced. This means a generator from another function can be addressed.
  1. <?php
  2. /**
  3. * Generator delegation
  4. */
  5.   
  6. function gen()
  7. {
  8.      yield 1;
  9.      yield 2;
  10.      yield from gen2();
  11. }
  12.   
  13. function gen2()
  14. {
  15.      yield 3;
  16.      yield 4;
  17. }
  18.   
  19. foreach (gen() as $val)
  20. {
  21.      echo $val, PHP_EOL;
  22. }
複製代碼


Generator return expressions
As mentioned: by using the yield keyword, values can be yielded and iterator over. But return values are ignored by generators.
In PHP 7 the “getReturn” method was added to the Generator class to allow return values in generators.

  1. <?php
  2. /**
  3. * Generator delegation
  4. */
  5.   
  6. function gen()
  7. {
  8.      yield 1;
  9.      yield 2;
  10.      yield from gen2();
  11. }
  12.   
  13. function gen2()
  14. {
  15.      yield 3;
  16.      yield 4;
  17. }
  18.   
  19. foreach (gen() as $val)
  20. {
  21.      echo $val, PHP_EOL;
  22. }
複製代碼

The null coalesce operator
The null coalesce operator is a shorthand for checking if a value is set and not null within inline comparisons.
Instead of doing the same old “isset” check over and over again,
just use “??” to return the value if it is set (and not null) or an alternative value instead.

  1. <?php
  2. /**
  3. * Null coalesce operator
  4. */
  5.   
  6. $array = ['foo'=>'bar'];
  7.   
  8. //PHP5 style
  9. $message = isset($array['foo']) ? $array['foo'] : 'not set';
  10. echo $message.PHP_EOL;
  11.   
  12. //PHP7 style
  13. $message = $array['foo'] ?? 'not set';
  14. echo $message.PHP_EOL;
複製代碼

The space ship operator
The so-called “space ship operator” makes it easier to compare values.
Instead of returning a typical true/false value, the space ship operator returns one of the follow values based on the result of the evaluation:

  • 0 when both values are equal
  • -1 when the left value is less than the right value
  • 1 if the left value is greater than the right value

   
  1. <?php
  2. /**
  3. * Space ship operator
  4. */
  5.   
  6. $array = [
  7.      "1 <=> 1" => 1 <=> 1,
  8.      "1 <=> 2" =>1 <=> 2,
  9.      "2 <=> 1" => 2 <=> 1
  10. ];
  11.   
  12. var_dump($array);
複製代碼

Throwables
A big change in PHP 7 is the fact that errors are no longer raised the way they used to be raised.
Errors now behave in a similar way as exceptions. They both inherit from the Throwable interface.
This means that errors can now be caught in a try/catch block.
You can catch both exceptions and errors as Throwables, but you can also catch errors as Error objects.
There are event different kinds of errors we can catch:


  1. <?php
  2. /**
  3. * Throwable interface
  4. */
  5.   
  6.   
  7. //Error as Throwable
  8. try {
  9.      sqdf();
  10. } catch (Throwable $t) {
  11.      echo "Throwable: ".$t->getMessage().PHP_EOL;
  12. }
  13.   
  14. //Exception as Throwable
  15. try {
  16.      throw new Exception("Bla");
  17. } catch (Throwable $t) {
  18.      echo "Throwable: ".$t->getMessage().PHP_EOL;
  19. }
  20.   
  21. //Error
  22. try {
  23.      sqdf();
  24. } catch (Error $e) {
  25.      echo "Error: ".$e->getMessage().PHP_EOL;
  26. } catch (Exception $e) {
  27.      echo "Exception: ".$e->getMessage().PHP_EOL;
  28. }
  29.   
  30. //Exception
  31. try {
  32.      throw new Exception("Bla");
  33. } catch (Error $e) {
  34.      echo "Error: ".$e->getMessage().PHP_EOL;
  35. } catch (Exception $e) {
  36.      echo "Exception: ".$e->getMessage().PHP_EOL;
  37. }
  38.   
  39. //Type error
  40. try {
  41.      function add(int $a, int $b):int {
  42.          return $a + $b;
  43.      }
  44.      echo add(array(), array());
  45. } catch (TypeError $t) {
  46.      echo "Type error: ".$t->getMessage().PHP_EOL;
  47. }
複製代碼

This is also a backwards compatibility break because custom error handlers might not be triggered. If you have a parse error in an eval function, it will throw a ParseError instead of just returning false. Watch out!
Level support for the dirname() function
The dirname function is used more often than you would think.
It is the ideal function to refer to directories in a relative way.
But when you want to go a couple of levels up, you end up nesting dirname calls and that will eventually lead to confusion.
As of PHP 7 the dirname function has a second argument that indicates how many levels your going up the directory tree.
If you don’t enter a value, 1 is the default.
  1. <?php
  2. /**
  3. * Dirname levels
  4. */
  5.   
  6. echo dirname('/usr/local/bin').PHP_EOL;
  7. echo dirname('/usr/local/bin',1).PHP_EOL;
  8. echo dirname('/usr/local/bin',2).PHP_EOL;
  9. echo dirname('/usr/local/bin',3).PHP_EOL;
複製代碼

The Integer division function
Maybe not the most important feature in PHP 7, but still worth mentioning:
the intdiv function returns the integer value of a division whereas regular divisions can result in a float being returned.

   
  1. <?php
  2. /**
  3. * Integer division
  4. */
  5.   
  6. var_dump(
  7.      intdiv(10, 3),
  8.      (10/3)
  9. );
複製代碼

Uniform variable syntax
In PHP 7 the “uniform variable syntax” was introduced.
This standard changes the way indirect access to array keys, properties and methods is evaluated.
The PHP 7 interpretation enforces a strict left-to-right evaluation.

This is also considered a backwards compatibility break.
It is advised to change your code and use curly braces to enforce the evaluation order if you want your code to work on PHP 7.
Performance
Let’s not forget to mention that the performance of PHP 7 is supposed to be impressive.
Some say that it’s twice as fast as PHP 5(.6) others use even more dazzling numbers.
I’m confident that it perform great and I’m curious to see the average numbers once people start using it.

分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-5-15 17:12 , Processed in 0.266750 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表