[TOC]
* * * * *
## PHP7性能
7最大的亮點,應該就是性能提高了兩倍,某些測試環境下甚至提高到三到五倍,具體可以了解以下鏈接:
[PHP7 VS HHVM (WordPress)](http://www.laruence.com/2014/12/18/2976.html)
[HHVM vs PHP 7 – The Competition Gets Closer! ](https://kinsta.com/blog/hhvm-vs-php-7/)
[PHP 7.0 Is Showing Very Promising Performance Over PHP 5, Closing Gap With HHVM](https://www.phoronix.com/scan.php?page=article&item=php-70-rc2&num=1)
[PHP7革新與性能優化](https://www.csdn.net/article/2015-09-16/2825720)
## 特性簡述
### 標量類型聲明
PHP 7 中的函數的形參類型聲明可以是標量了。在 PHP 5 中只能是類名、接口、array 或者 callable (PHP 5.4,即可以是函數,包括匿名函數),**現在也可以使用 string、int、float和 bool 了**。
```php
<?php
// 強制模式,強制把參數int化
function sumOfInts(int ...$ints)
{
return array_sum($ints);
}
var_dump(sumOfInts(2, '3', 4.1));
```
> 強制模式(默認,既強制類型轉換)下會對不符合預期的參數進行強制類型轉換,但嚴格模式下則觸發 **TypeError 的致命錯誤。**
> 嚴格模式:申明 declare(strict_types=1)即可;
### 返回值類型聲明
PHP 7 增加了對返回類型聲明的支持。 類似于參數類型聲明,返回類型聲明指明了函數返回值的類型。可用的類型與參數聲明中可用的類型相同。
```php
<?php
function arraysSum(array ...$arrays): array
{
# 把返回值強制轉換為string
return array_map(function(array $array): string {
return array_sum($array);
}, $arrays);
}
var_dump(arraysSum([1,2,3], [4,5,6], [7,8,9]));
# output
array(3) {
[0]=>
string(1) "6"
[1]=>
string(2) "15"
[2]=>
string(2) "24"
}
```
> 同樣有嚴格模式和強制模式
### NULL 合并運算符
```php
// 如果 $_GET['user'] 不存在返回 'nobody',否則返回 $_GET['user'] 的值
$username = $_GET['user'] ?? 'nobody';
// 相當于
isset($_GET['user']) ? $_GET['user'] : 'nobody';
// 類似于屏蔽notice錯誤后的:
$username = $_GET['user'] ?: 'nobody';
```
### 太空船操作符(組合比較符)
用于比較兩個表達式。當$a大于、等于或小于$b時它分別返回-1、0或1。
```php
<?php
// $a 是否大于 $b , 大于就返回1
// 整型
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
```
### 通過 define() 定義常量數組
```php
<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
// ANIMALS[1] = mouse; 常量數組里面的值,是不可以更改的
echo ANIMALS[1]; // 輸出 "cat"
```
### 匿名類
現在支持通過new class 來實例化一個匿名類
```php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});
var_dump($app->getLogger());
# output:
object(class@anonymous)#2 (0) {
}
```
### 為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]);
```
### 斷言assert
向后兼用并增強之前的 assert() 的方法。 它使得在生產環境中啟用斷言為零成本,并且提供當斷言失敗時拋出特定異常的能力。
```php
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(2 == 1, new CustomError('Some error message'));
```
### use 加強
從同一 namespace 導入的類、函數和常量現在可以通過單個 use 語句 一次性導入了。
```php
// PHP 7 之前版本用法
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// PHP 7+ 用法
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
```
### Generator 加強 : yield from
增強了Generator的功能,這個可以實現很多先進的特性
```php
function gen()
{
yield 1;
yield 2;
yield from gen2();
}
function gen2()
{
yield 3;
yield 4;
}
foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
```
### 整除
新增了整除函數 intdiv()
```php
var_dump(intdiv(10, 3)); # 3
```
### array_column() 和 list()
新增支持對象數組
```php
list($a, $b) = (object) new ArrayObject([0, 1]);
```
> PHP7結果:$a == 0 and $b == 1.
> PHP5結果:$a == null and $b == null.
### dirname()
增加了可選項$levels,可以用來指定目錄的層級。dirname(dirname($foo)) => dirname($foo, 2);
### Closure::call()
Closure::call() 現在有著更好的性能,簡短干練的**暫時綁定一個方法到對象上閉包并調用它。**
```php
class A {private $x = 1;}
// Pre PHP 7 代碼
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A');
echo $getX();
//// PHP 7+ 代碼
$getX = function() {return $this->x;};
echo $getX->call(new A);
```
### Unicode codepoint 轉譯語法
```php
echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";
```
更多請參考:
[關于PHP7新特性](http://www.php7.site/book/php7/about-30.html)
- 現代化PHP特性
- php7常用特性整理
- 反射機制Reflection
- 依賴注入與服務容器
- 抽象類與接口
- 類多繼承的替代方案Traits
- 類的延遲綁定(后期綁定)
- 生成器語法
- 匿名函數和閉包
- 匿名類
- 理解php的output buffer
- 斷言ASSERT
- 魔術方法小結
- Zend Opcache字節碼緩存
- 內置的http服務器
- SPL標準庫
- 【SPL標準庫專題(1)】SPL簡介
- 【SPL標準庫專題(2)】Iterator
- 【SPL標準庫專題(3)】Classes
- 【SPL標準庫專題(4)】Exceptions
- 【SPL標準庫專題(5)】Datastructures:SplDoublyLinkedList
- 【SPL標準庫專題(6)】Datastructures:SplStack & SplQueue
- 【SPL標準庫專題(7)】Datastructures:SplPriorityQueue
- 【SPL標準庫專題(8)】Datastructures:SplHeap & SplMaxHeap & SplMinHeap
- 【SPL標準庫專題(9)】Datastructures:SplFixedArray
- 【SPL標準庫專題(10)】Datastructures:SplObjectStorage
- PHPcomposer使用手札[ing]
- PHP中的多態
- 通過命名空間實現自動加載的框架雛形
- 日期與金額
- PHPstorm使用攻略
- 筆記本