PHP7 已經(jīng)出來1年了,PHP7.1也即將和大家見面,這么多好的特性,好的方法,為什么不使用呢,也希望PHP越來越好。
在這里整理php5.1 ,PHP5.2,PHP5.3,PHP5.4,PHP5.5,PHP5.6 ,PHP7,PHP7.1 所有新特性,已備大家學(xué)習(xí)及使用
PHP5.1~PHP5.6http://blog.csdn.net/fenglailea/article/details/9853645
PHP7~PHP7.1
http://blog.csdn.net/fenglailea/article/details/52717364
風(fēng).fox
Buid-in web server內(nèi)置了一個簡單的Web服務(wù)器
把當前目錄作為Root Document只需要這條命令即可:
php-Slocalhost:3300
也可以指定其它路徑
php-Slocalhost:3300-t/path/to/root
還可以指定路由
php-Slocalhost:3300router.php
命名空間的分隔符為反斜桿\
namespacefox\lanmps\Table;classSelect{}
PHP5.3 中引入命名空間的別名類和命名空間短版本的功能。雖然這并不適用于字符串類名稱
use Some\Deeply\Nested\Namespace\FooBar;//doesnotwork, becausethiswilltryto use theglobal`FooBar`class$reflection =newReflectionClass('FooBar');? echoFooBar::class;
為了解決這個問題采用新的FooBar::class語法,它返回類的完整類別名稱
命名空間 use 操作符開始支持函數(shù)和常量的導(dǎo)入
namespaceName\Space{constFOO= 42;functionf(){echo__FUNCTION__."\n"; }? }namespace{useconstName\Space\FOO;usefunctionName\Space\f;echoFOO."\n";? ? ? f();? }
輸出
42
Name\Space\f
從同一 namespace 導(dǎo)入的類、函數(shù)和常量現(xiàn)在可以通過單個 use 語句 一次性導(dǎo)入了。
//PHP7之前usesome\namespace\ClassA;usesome\namespace\ClassB;usesome\namespace\ClassCasC;usefunctionsome\namespace\fn_a;usefunctionsome\namespace\fn_b;usefunctionsome\namespace\fn_c;useconst some\namespace\ConstA;useconst some\namespace\ConstB;useconst some\namespace\ConstC;// PHP7之后usesome\namespace\{ClassA, ClassB, ClassCasC};usefunctionsome\namespace\{fn_a, fn_b, fn_c};useconst some\namespace\{ConstA, ConstB, ConstC};
static關(guān)鍵字來引用當前類,即實現(xiàn)了延遲靜態(tài)綁定
classA{publicstaticfunctionwho(){echo__CLASS__;? ? ? ? }publicstaticfunctiontest(){static::who();// 這里實現(xiàn)了延遲的靜態(tài)綁定}? ? }classBextendsA{publicstaticfunctionwho(){echo__CLASS__;? ? ? ? }? ? }B::test();
輸出結(jié)果:
B
多數(shù)計算機程序設(shè)計語言中都支持無條件轉(zhuǎn)向語句goto,當程序執(zhí)行到goto語句時,即轉(zhuǎn)向由goto語句中的標號指出的程序位置繼續(xù)執(zhí)行。盡管goto語句有可能會導(dǎo)致程序流程不清晰,可讀性減弱,但在某些情況下具有其獨特的方便之處,例如中斷深度嵌套的循環(huán)和 if 語句。
gotoa;echo'Foo';? ? a:echo'Bar';for($i=0,$j=50;$i<100;$i++) {while($j--) {if($j==17)gotoend;? ? ? }? ? }echo"i = $i";? ? end:echo'j hit 17';
閉包(Closure)函數(shù)和Lambda函數(shù)的概念來自于函數(shù)編程領(lǐng)域。例如JavaScript是支持閉包和 lambda 函數(shù)的最常見語言之一。
在PHP中,我們也可以通過create_function()在代碼運行時創(chuàng)建函數(shù)。但有一個問題:創(chuàng)建的函數(shù)僅在運行時才被編譯,而不與其它代碼同時被編譯成執(zhí)行碼,因此我們無法使用類似APC這樣的執(zhí)行碼緩存來提高代碼執(zhí)行效率。
在PHP5.3中,我們可以使用Lambda/匿名函數(shù)來定義一些臨時使用(即用即棄型)的函數(shù),以作為array_map()/array_walk()等函數(shù)的回調(diào)函數(shù)。
echopreg_replace_callback('~-([a-z])~',function($match){returnstrtoupper($match[1]);? ? },'hello-world');// 輸出 helloWorld$greet=function($name){printf("Hello %s\r\n",$name);? ? };$greet('World');$greet('PHP');//...在某個類中$callback=function($quantity,$product)use($tax, &$total){$pricePerItem= constant(__CLASS__."::PRICE_".? strtoupper($product));$total+= ($pricePerItem*$quantity) * ($tax+1.0);? ? };
魔術(shù)方法__callStatic()和__invoke()
PHP中原本有一個魔術(shù)方法__call(),當代碼調(diào)用對象的某個不存在的方法時該魔術(shù)方法會被自動調(diào)用。新增的__callStatic()方法則只用于靜態(tài)類方法。當嘗試調(diào)用類中不存在的靜態(tài)方法時,__callStatic()魔術(shù)方法將被自動調(diào)用。
classMethodTest{publicfunction__call($name,$arguments){// 參數(shù) $name 大小寫敏感echo"調(diào)用對象方法 '$name' ". implode(' -- ',$arguments)."\n";? ? ? ? }/**? PHP 5.3.0 以上版本中本類方法有效? */publicstaticfunction__callStatic($name,$arguments){// 參數(shù) $name 大小寫敏感echo"調(diào)用靜態(tài)方法 '$name' ". implode(' -- ',$arguments)."\n";? ? ? ? }? ? }$obj=newMethodTest;$obj->runTest('通過對象調(diào)用');? ? MethodTest::runTest('靜態(tài)調(diào)用');// As of PHP 5.3.0
以上代碼執(zhí)行后輸出如下:
調(diào)用對象方法’runTest’ –- 通過對象調(diào)用調(diào)用靜態(tài)方法’runTest’ –- 靜態(tài)調(diào)用
以函數(shù)形式來調(diào)用對象時,__invoke()方法將被自動調(diào)用。
classMethodTest{publicfunction__call($name,$arguments){// 參數(shù) $name 大小寫敏感echo"Calling object method '$name' ". implode(', ',$arguments)."\n";? ? ? ? }/**? PHP 5.3.0 以上版本中本類方法有效? */publicstaticfunction__callStatic($name,$arguments){// 參數(shù) $name 大小寫敏感echo"Calling static method '$name' ". implode(', ',$arguments)."\n";? ? ? ? }? ? }$obj=newMethodTest;$obj->runTest('in object context');? ? MethodTest::runTest('in static context');// As of PHP 5.3.0
用法和Heredoc類似,但使用單引號。Heredoc則需要通過使用雙引號來聲明。
Nowdoc中不會做任何變量解析,非常適合于傳遞一段PHP代碼。
// Nowdoc 單引號 PHP 5.3之后支持$name='MyName';echo<<<'EOT'My name is"$name".? ? EOT;//上面代碼輸出 My name is "$name". ((其中變量不被解析)// Heredoc不加引號echo<<
支持通過Heredoc來初始化靜態(tài)變量、類成員和類常量。
// 靜態(tài)變量functionfoo(){static$bar= <<
//PHP中定義常量通常是用這種方式define("CONSTANT","Hello world.");//并且新增了一種常量定義方式const CONSTANT='Hello World';
原本格式為是(expr1) ? (expr2) : (expr3)
如果expr1結(jié)果為True,則返回expr2的結(jié)果。
新增一種書寫方式,可以省略中間部分,書寫為expr1 ?: expr3
如果expr1結(jié)果為True,則返回expr1的結(jié)果
$expr1=1;$expr2=2;//原格式$expr=$expr1?$expr1:$expr2//新格式$expr=$expr1?:$expr2
輸出結(jié)果:
1
1
簡化判斷
$param=$_GET['param'] ??1;
相當于:
$param=isset($_GET['param']) ?$_GET['param'] :1;
Json更懂中文(JSON_UNESCAPED_UNICODE)
echojson_encode("中文", JSON_UNESCAPED_UNICODE);? //輸出:"中文"
$bin=0b1101;echo$bin;//13
這接受一個以16進制形式的 Unicode codepoint,并打印出一個雙引號或heredoc包圍的 UTF-8 編碼格式的字符串。 可以接受任何有效的 codepoint,并且開頭的 0 是可以省略的。
echo"\u{9876}"
舊版輸出:\u{9876}
新版輸入:頂
加入右連接運算符* 來進行冪運算。 同時還支持簡寫的 *= 運算符,表示進行冪運算并賦值。
printf("2**3 ==%d\n",2**3);printf("2**3**2 ==%d\n",2**3**2);$a=2;$a**=3;printf("a ==%d\n",$a);
輸出
2 ** 3 == 8
2* 3 *2 == 512
a == 8
太空船操作符用于比較兩個表達式。當a大于、等于或小于b 時它分別返回 -1 、 0 或 1 。 比較的原則是沿用 PHP 的常規(guī)比較規(guī)則進行的。
// Integersecho1<=>1;// 0echo1<=>2;// -1echo2<=>1;// 1// Floatsecho1.5<=>1.5;// 0echo1.5<=>2.5;// -1echo2.5<=>1.5;// 1// Stringsecho"a"<=>"a";// 0echo"a"<=>"b";// -1echo"b"<=>"a";// 1
Traits提供了一種靈活的代碼重用機制,即不像interface一樣只能定義方法但不能實現(xiàn),又不能像class一樣只能單繼承。至于在實踐中怎樣使用,還需要深入思考。
魔術(shù)常量為TRAIT
官網(wǎng)的一個例子:traitSayWorld {publicfunctionsayHello(){parent::sayHello();echo"World!\n";echo'ID:'.$this->id ."\n";? ? ? ? ? }? }classBase{publicfunctionsayHello(){echo'Hello ';? ? ? ? ? }? }classMyHelloWorldextendsBase{private$id;publicfunction__construct(){$this->id =123456;? ? ? ? ? }useSayWorld;? }$o=newMyHelloWorld();$o->sayHello();/*will output:
Hello World!
ID:123456
*/
$arr= [1,'james','james@fwso.cn'];$array= ["foo"=>"bar","bar"=>"foo"];
functionmyfunc(){returnarray(1,'james','james@fwso.cn');? }echomyfunc()[1];$name= explode(",","Laruence,male")[0];? explode(",","Laruence,male")[3] ="phper";
echo array(1, 2, 3)[0];? echo [1, 2, 3][0];? echo "foobar"[2];
現(xiàn)在所有接偏移量的內(nèi)置的基于字符串的函數(shù)都支持接受負數(shù)作為偏移量,包括數(shù)組解引用操作符([]).
var_dump("abcdef"[-2]);var_dump(strpos("aabbcc","b", -3));
以上例程會輸出:
string(1)"e"int(3)
“常量引用”意味著數(shù)組可以直接操作字符串和數(shù)組字面值。舉兩個例子:
functionrandomHexString($length){$str='';for($i=0;$i<$length; ++$i) {$str.="0123456789abcdef"[mt_rand(0,15)];// direct dereference of string}? ? }functionrandomBool(){return[false,true][mt_rand(0,1)];// direct dereference of array}
允許常量計算,允許使用包含數(shù)字、字符串字面值和常量的標量表達式
constA =2;constB = A +1;classC{constSTR ="hello";constSTR2 =self::STR +", world";? }
允許常量作為函數(shù)參數(shù)默認
functiontest($arg = C::STR2)
類常量可見性
現(xiàn)在起支持設(shè)置類常量的可見性。
class ConstDemo{constPUBLIC_CONST_A =1;publicconstPUBLIC_CONST_B =2;protectedconstPROTECTED_CONST =3;privateconstPRIVATE_CONST =4;}
define('ANIMALS', ['dog','cat','bird']);echo ANIMALS[1];// outputs "cat"
兩種模式 : 強制 ( 默認 ) 和 嚴格模式
類型:array,object(對象),string、int、float和 bool
classbar{functionfoo(bar$foo){}//其中函數(shù)foo中的參數(shù)規(guī)定了傳入的參數(shù)必須為bar類的實例,否則系統(tǒng)會判斷出錯。同樣對于數(shù)組來說,也可以進行判斷,比如:functionfoo(array$foo){}? }? foo(array(1,2,3));// 正確,因為傳入的是數(shù)組foo(123);// 不正確,傳入的不是數(shù)組functionadd(int$a){return1+$a; } var_dump(add(2));functionfoo(int$i){... }? foo(1);// $i = 1foo(1.0);// $i = 1foo("1");// $i = 1foo("1abc");// not yet clear, maybe $i = 1 with noticefoo(1.5);// not yet clear, maybe $i = 1 with noticefoo([]);// errorfoo("abc");// error
如果你有一個函數(shù)接受多個可選的參數(shù),目前沒有辦法只改變最后一個參數(shù),而讓其他所有參數(shù)為默認值。
RFC上的例子,如果你有一個函數(shù)如下:
functioncreate_query($where, $order_by, $join_type='', $execute = false, $report_errors = true) {...}
那么有沒有辦法設(shè)置$report_errors=false,而其他兩個為默認值。為了解決這個跳躍參數(shù)的問題而提出:
create_query("deleted=0","name",default,default,false);
代替 func_get_args()
functionadd(...$args){$result =0;? ? ? foreach($argsas$arg)? ? ? ? ? $result += $arg;return$result;? }
類型現(xiàn)在允許為空,當啟用這個特性時,傳入的參數(shù)或者函數(shù)返回的結(jié)果要么是給定的類型,要么是 null 。可以通過在類型前面加上一個問號來使之成為可為空的。
functiontest(?string$name){var_dump($name);}
以上例程會輸出:
string(5)"tpunt"NULLUncaughtError: Too few argumentstofunctiontest(),0passedin...
在PHP 7 中引入的其他返回值類型的基礎(chǔ)上,一個新的返回值類型void被引入。 返回值聲明為 void 類型的方法要么干脆省去 return 語句,要么使用一個空的 return 語句。 對于 void 函數(shù)來說,null 不是一個合法的返回值。
functionswap(&$left, &$right):void{if($left===$right) {return;? ? }$tmp=$left;$left=$right;$right=$tmp;}$a=1;$b=2;var_dump(swap($a,$b),$a,$b);
以上例程會輸出:
nullint(2)int(1)
試圖去獲取一個 void 方法的返回值會得到 null ,并且不會產(chǎn)生任何警告。這么做的原因是不想影響更高層次的方法。
函數(shù)和匿名函數(shù)都可以指定返回值的類型
functionshow(): array{return[1,2,3,4]; }functionarraysSum(array...$arrays): array{returnarray_map(function(array $array): int{returnarray_sum($array);}, $arrays);}
在調(diào)用函數(shù)的時候,通過 … 操作符可以把數(shù)組或者可遍歷對象解包到參數(shù)列表,這和Ruby等語言中的擴張(splat)操作符類似
functionadd($a,$b,$c){return$a+$b+$c;? }$arr= [2,3];? add(1, ...$arr);
classtest{functionshow(){return'test';? ? ? }? }? echo(newtest())->show();
foreach([newHuman("Gonzalo"),newHuman("Peter")]as$human) {echo$human->{'hello'}();? }
functionfoo(callable$callback){}
則
foo("false");//錯誤,因為false不是callable類型foo("printf");//正確foo(function(){});//正確classA{staticfunctionshow(){}? }? foo(array("A","show"));//正確
如果你從不喜歡寫這些getXYZ()和setXYZ($value)方法,那么這應(yīng)該是你最受歡迎的改變。提議添加一個新的語法來定義一個屬性的設(shè)置/讀取:
class TimePeriod {public$seconds;public$hours{? ? ? ? ? get {return$this->seconds/3600; }set{$this->seconds=$value*3600; }? ? ? }? }$timePeriod=newTimePeriod;$timePeriod->hours=10;? var_dump($timePeriod->seconds);// int(36000)var_dump($timePeriod->hours);// int(10)
目前,自定義迭代器很少使用,因為它們的實現(xiàn),需要大量的樣板代碼。生成器解決這個問題,并提供了一種簡單的樣板代碼來創(chuàng)建迭代器。
例如,你可以定義一個范圍函數(shù)作為迭代器:
function*xrange($start,$end,$step=1){for($i=$start;$i<$end;$i+=$step) {yield$i;? ? ? }? }foreach(xrange(10,20)as$i) {// ...}
上述xrange函數(shù)具有與內(nèi)建函數(shù)相同的行為,但有一點區(qū)別:不是返回一個數(shù)組的所有值,而是返回一個迭代器動態(tài)生成的值。
列表解析提供一個簡單的方法對數(shù)組進行小規(guī)模操作:
$firstNames= [foreach($usersas$user)yield$user->firstName];
上述列表解析相等于下面的代碼:
$firstNames= [];foreach($usersas$user) {$firstNames[] =$user->firstName;? }
也可以這樣過濾數(shù)組:
$underageUsers= [foreach($usersas$user)if($user->age <18)yield$user];
生成器表達式也很類似,但是返回一個迭代器(用于動態(tài)生成值)而不是一個數(shù)組。
在PHP5.5引入生成器的概念。生成器函數(shù)每執(zhí)行一次就得到一個yield標識的值。在PHP7中,當生成器迭代完成后,可以獲取該生成器函數(shù)的返回值。通過Generator::getReturn()得到。
functiongenerator(){yield1;yield2;yield3;return"a";}$generatorClass= ("generator")();foreach($generatorClassas$val) {echo$val." ";}echo$generatorClass->getReturn();
輸出為:1 2 3 a
在生成器中可以引入另一個或幾個生成器,只需要寫yield from functionName1
functiongenerator1(){yield1;yield2;yieldfrom generator2();yieldfrom generator3();}functiongenerator2(){yield3;yield4;}functiongenerator3(){yield5;yield6;}foreach(generator1()as$val) {echo$val," ";}
輸出:1 2 3 4 5 6
這個和Java中的finally一樣,經(jīng)典的try … catch … finally 三段式異常處理。
一個catch語句塊現(xiàn)在可以通過管道字符(|)來實現(xiàn)多個異常的捕獲。 這對于需要同時處理來自不同類的不同異常時很有用。
try{// some code}catch(FirstException | SecondException$e) {// handle first and second exceptions}catch(\Exception$e) {// ...}finally{//}
對于“數(shù)組的數(shù)組”進行迭代,之前需要使用兩個foreach,現(xiàn)在只需要使用foreach + list了,但是這個數(shù)組的數(shù)組中的每個數(shù)組的個數(shù)需要一樣。看文檔的例子一看就明白了。
$array= [? ? ? [1,2],? ? ? [3,4],? ];foreach($arrayaslist($a,$b)) {echo"A: $a; B: $b\n";? }
短數(shù)組語法 Symmetric array destructuring
短數(shù)組語法([])現(xiàn)在可以用于將數(shù)組的值賦給一些變量(包括在foreach中)。 這種方式使從數(shù)組中提取值變得更為容易。
$data= [? ? ['id'=>1,'name'=>'Tom'],? ? ['id'=>2,'name'=>'Fred'],];while(['id'=>$id,'name'=>$name] =$data) {// logic here with $id and $name}
現(xiàn)在list()支持在它內(nèi)部去指定鍵名。這意味著它可以將任意類型的數(shù)組 都賦值給一些變量(與短數(shù)組語法類似)
$data= [? ? ['id'=>1,'name'=>'Tom'],? ? ['id'=>2,'name'=>'Fred'],];while(list('id'=>$id,'name'=>$name) =$data) {// logic here with $id and $name}
現(xiàn)在引入了一個新的被稱為iterable的偽類 (與callable類似)。 這可以被用在參數(shù)或者返回值類型中,它代表接受數(shù)組或者實現(xiàn)了Traversable接口的對象。 至于子類,當用作參數(shù)時,子類可以收緊父類的iterable類型到array 或一個實現(xiàn)了Traversable的對象。對于返回值,子類可以拓寬父類的 array或?qū)ο蠓祷刂殿愋偷絠terable。
functioniterator(iterable$iter){foreach($iteras$val) {//}}
通過給openssl_encrypt()和openssl_decrypt() 添加額外參數(shù),現(xiàn)在支持了AEAD (模式 GCM and CCM)。
通過 Closure::fromCallable() 將callables轉(zhuǎn)為閉包
Closure新增了一個靜態(tài)方法,用于將callable快速地 轉(zhuǎn)為一個Closure 對象。
classTest{publicfunctionexposeFunction(){returnClosure::fromCallable([$this,'privateFunction']);? ? }privatefunctionprivateFunction($param){var_dump($param);? ? }}$privFunc= (newTest)->exposeFunction();$privFunc('some value');
以上例程會輸出:
string(10)"some value"
現(xiàn)在支持通過 new class 來實例化一個匿名類,這可以用來替代一些“用后即焚”的完整類定義。
interfaceLogger{publicfunctionlog(string$msg);}classApplication{private$logger;publicfunctiongetLogger():Logger{return$this->logger;? ? }publicfunctionsetLogger(Logger$logger){$this->logger =$logger;? ? }}$app=newApplication;$app->setLogger(newclassimplementsLogger{publicfunctionlog(string$msg){echo$msg;? ? }});var_dump($app->getLogger());
Closure::call() 現(xiàn)在有著更好的性能,簡短干練的暫時綁定一個方法到對象上閉包并調(diào)用它。
classTest{public$name="lixuan";}//PHP7和PHP5.6都可以$getNameFunc=function(){return$this->name;};$name=$getNameFunc->bindTo(newTest,'Test');echo$name();//PHP7可以,PHP5.6報錯$getX=function(){return$this->name;};echo$getX->call(newTest);
這個特性旨在提供更安全的方式解包不可靠的數(shù)據(jù)。它通過白名單的方式來防止?jié)撛诘拇a注入。
//將所有對象分為__PHP_Incomplete_Class對象$data= unserialize($foo, ["allowed_classes"=>false]);//將所有對象分為__PHP_Incomplete_Class 對象 除了ClassName1和ClassName2$data= unserialize($foo, ["allowed_classes"=> ["ClassName1","ClassName2"]);//默認行為,和 unserialize($foo)相同$data= unserialize($foo, ["allowed_classes"=>true]);
新增加的 IntlChar 類旨在暴露出更多的 ICU 功能。這個類自身定義了許多靜態(tài)方法用于操作多字符集的 unicode 字符。Intl是Pecl擴展,使用前需要編譯進PHP中,也可apt-get/yum/port install php5-intl
printf('%x', IntlChar::CODEPOINT_MAX);echo IntlChar::charName('@');var_dump(IntlChar::ispunct('!'));
以上例程會輸出:
10ffff
COMMERCIAL AT
bool(true)
預(yù)期是向后兼用并增強之前的 assert() 的方法。 它使得在生產(chǎn)環(huán)境中啟用斷言為零成本,并且提供當斷言失敗時拋出特定異常的能力。 老版本的API出于兼容目的將繼續(xù)被維護,assert()現(xiàn)在是一個語言結(jié)構(gòu),它允許第一個參數(shù)是一個表達式,而不僅僅是一個待計算的 string或一個待測試的boolean。
ini_set('assert.exception',1);classCustomErrorextendsAssertionError{}assert(false,newCustomError('Some error message'));
以上例程會輸出:
Fatal error: Uncaught CustomError: Some error message
接收兩個參數(shù)作為被除數(shù)和除數(shù),返回他們相除結(jié)果的整數(shù)部分。
var_dump(intdiv(7,2));
輸出int(3)
新增兩個函數(shù): random_bytes() and random_int().可以加密的生產(chǎn)被保護的整數(shù)和字符串。總之隨機數(shù)變得安全了。
random_bytes — 加密生存被保護的偽隨機字符串
random_int —加密生存被保護的偽隨機整數(shù)
新增了一個函數(shù)preg_replace_callback_array(),使用該函數(shù)可以使得在使用preg_replace_callback()函數(shù)時代碼變得更加優(yōu)雅。在PHP7之前,回調(diào)函數(shù)會調(diào)用每一個正則表達式,回調(diào)函數(shù)在部分分支上是被污染了。
現(xiàn)在,session_start()函數(shù)可以接收一個數(shù)組作為參數(shù),可以覆蓋php.ini中session的配置項。
比如,把cache_limiter設(shè)置為私有的,同時在閱讀完session后立即關(guān)閉。
session_start(['cache_limiter'=>'private','read_and_close'=>true,]);
$_SERVER[“REQUEST_TIME_FLOAT”]
這個是用來統(tǒng)計服務(wù)請求時間的,并用ms(毫秒)來表示
echo"腳本執(zhí)行時間 ", round(microtime(true) -$_SERVER["REQUEST_TIME_FLOAT"],2),"s";
empty() 現(xiàn)在支持傳入一個任意表達式,而不僅是一個變量
functionalways_false(){returnfalse;}if(empty(always_false())) {echo'This will be printed.';}if(empty(true)) {echo'This will not be printed.';}
輸出
This will be printed.
php://input 開始支持多次打開和讀取,這給處理POST數(shù)據(jù)的模塊的內(nèi)存占用帶來了極大的改善。
Session提供了上傳進度支持,通過$_SESSION[“upload_progress_name”]就可以獲得當前文件上傳的進度信息,結(jié)合Ajax就能很容易實現(xiàn)上傳進度條了。
詳細的看http://www.laruence.com/2011/10/10/2217.html
可以上傳超過2G的大文件。
GMP 對象支持操作符重載和轉(zhuǎn)換為標量,改善了代碼的可讀性,如:
$a= gmp_init(42);$b= gmp_init(17);//Pre-5.6code:var_dump(gmp_add($a,$b));? var_dump(gmp_add($a,17));? var_dump(gmp_add(42,$b));//Newcode:var_dump($a+$b);? var_dump($a+17);? var_dump(42+$b);
實現(xiàn)了JsonSerializable接口的類的實例在json_encode序列化的之前會調(diào)用jsonSerialize方法,而不是直接序列化對象的屬性。
參考http://www.laruence.com/2011/10/10/2204.html
HTTP狀態(tài)碼在200-399范圍內(nèi)均被認為訪問成功
classTest{publicstaticfunctiontestgo(){echo"gogo!";? ? ? ? }? ? }$class='Test';$action='testgo';$class::$action();//輸出 "gogo!"
e修飾符是指示preg_replace函數(shù)用來評估替換字符串作為PHP代碼,而不只是僅僅做一個簡單的字符串替換。不出所料,這種行為會源源不斷的出現(xiàn)安全問題。這就是為什么在PHP5.5 中使用這個修飾符將拋出一個棄用警告。作為替代,你應(yīng)該使用preg_replace_callback函數(shù)。你可以從RFC找到更多關(guān)于這個變化相應(yīng)的信息。
PHP已經(jīng)實現(xiàn)了strval、intval和floatval的函數(shù)。為了達到一致性將添加boolval函數(shù)。它完全可以作為一個布爾值計算,也可以作為一個回調(diào)函數(shù)。
PBKDF2全稱“Password-Based Key Derivation Function 2”,正如它的名字一樣,是一種從密碼派生出加密密鑰的算法。這就需要加密算法,也可以用于對密碼哈希。更廣泛的說明和用法示例
//從數(shù)據(jù)庫獲取一列,但返回是數(shù)組。$userNames= [];foreach($usersas$user) {$userNames[] =$user['name'];? }//以前獲取數(shù)組某列值,現(xiàn)在如下$userNames= array_column($users,'name');
$password="foo";//creating the hash$hash= password_hash($password,PASSWORD_BCRYPT);//verifying a passwordif(password_verify($password,$hash)) {//password correct!? ? }else{//password wrong!? ? }
異步信號處理 Asynchronous signal handling
A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).
增加了一個新函數(shù) pcntl_async_signals()來處理異步信號,不需要再使用ticks(它會增加占用資源)
pcntl_async_signals(true);// turn on async signalspcntl_signal(SIGHUP,function($sig){echo"SIGHUP\n";});posix_kill(posix_getpid(), SIGHUP);
以上例程會輸出:
SIGHUP
Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUST_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied.
蹩腳英語:
對于服務(wù)器推送支持添加到curl擴展(需要7.46及以上版本)。
可以通過用新的CURLMOPT_PUSHFUNCTION常量 讓curl_multi_setopt()函數(shù)使用。
也增加了常量CURL_PUST_OK和CURL_PUSH_DENY,可以批準或拒絕 服務(wù)器推送回調(diào)的執(zhí)行
PHP default_charset 默認字符集 為UTF-8
在過去如果我們調(diào)用一個用戶定義的函數(shù)時,提供的參數(shù)不足,那么將會產(chǎn)生一個警告(warning)。 現(xiàn)在,這個警告被提升為一個錯誤異常(Error exception)。這個變更僅對用戶定義的函數(shù)生效, 并不包含內(nèi)置函數(shù)。例如:
functiontest($param){}test();
輸出:
UncaughtError: Too few argumentstofunctiontest(),0passedin%sonline %dandexactly1expectedin%s:%d
禁止動態(tài)調(diào)用函數(shù)如下
assert() - with a string as the first argument
compact()
extract()
func_get_args()
func_get_arg()
func_num_args()
get_defined_vars()
mb_parse_str() - with one arg
parse_str() - with one arg
(function(){? ? 'func_num_args'();})();
輸出
Warning: Cannotcallfunc_num_args() dynamicallyin%sonline %d
以下名稱不能用于 類,接口或trait 名稱命名:
void
iterable
4.Numerical string conversions now respect scientific notation
Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().
mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_srand() was relied upon, then the MT_RAND_PHP with the ability to preserve the old (incorrect) implementation via an additional optional second parameter to mt_srand().
6.rand() 別名 mt_rand() 和 srand() 別名 mt_srand()
rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changes: rand(), shuffle(), str_shuffle(), and array_rand().
7.Disallow the ASCII delete control character in identifiers
The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.
8.error_log changes with syslog value
If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.
析構(gòu)方法在一個不完整的對象(例如在構(gòu)造方法中拋出一個異常)上將不再會被調(diào)用
10.call_user_func()不再支持對傳址的函數(shù)的調(diào)用
call_user_func() 現(xiàn)在在調(diào)用一個以引用作為參數(shù)的函數(shù)時將始終失敗。
11.字符串不再支持空索引操作符 The empty index operator is not supported for strings anymore
對字符串使用一個空索引操作符(例如str[]=x)將會拋出一個致命錯誤, 而不是靜默地將其轉(zhuǎn)為一個數(shù)組
下列ini配置項已經(jīng)被移除:
session.entropy_file
session.entropy_length
session.hash_function
session.hash_bits_per_character
在PHP7之前,當數(shù)組通過 foreach 迭代時,數(shù)組指針會移動。現(xiàn)在開始,不再如此,見下面代碼。
$array= [0,1,2];foreach($arrayas&$val) {? ? var_dump(current($array));}
PHP5輸出:
int(1)
int(2)
bool(false)
PHP7輸出:
int(0)
int(0)
int(0)
當使用引用遍歷數(shù)組時,現(xiàn)在 foreach 在迭代中能更好的跟蹤變化。例如,在迭代中添加一個迭代值到數(shù)組中,參考下面的代碼:
$array= [0];foreach($arrayas&$val) {? ? var_dump($val);$array[1] =1;}
PHP5輸出:
int(0)
PHP7輸出:
int(0)
int(1)
含十六進制字符串不再被認為是數(shù)字
var_dump("0x123"=="291");var_dump(is_numeric("0x123"));var_dump("0xe"+"0x1");var_dump(substr("foo","0x1"));
PHP5輸出:
bool(true)
bool(true)
int(15)
string(2) “oo”
PHP7輸出:
bool(false)
bool(false)
int(0)
Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) “foo”
被移除的函數(shù)列表如下:
call_user_func() 和 call_user_func_array()從PHP 4.1.0開始被廢棄。
已廢棄的 mcrypt_generic_end() 函數(shù)已被移除,請使用mcrypt_generic_deinit()代替。
已廢棄的 mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() 和 mcrypt_ofb() 函數(shù)已被移除。
set_magic_quotes_runtime(), 和它的別名 magic_quotes_runtime()已被移除. 它們在PHP 5.3.0中已經(jīng)被廢棄,并且 在in PHP 5.4.0也由于魔術(shù)引號的廢棄而失去功能。
已廢棄的 set_socket_blocking() 函數(shù)已被移除,請使用stream_set_blocking()代替。
dl()在 PHP-FPM 不再可用,在 CLI 和 embed SAPIs 中仍可用。
GD庫中下列函數(shù)被移除:imagepsbbox()、imagepsencodefont()、imagepsextendfont()、imagepsfreefont()、imagepsloadfont()、imagepsslantfont()、imagepstext()
在配置文件php.ini中,always_populate_raw_post_data、asp_tags、xsl.security_prefs被移除了。
5、new 操作符創(chuàng)建的對象不能以引用方式賦值給變量
new 操作符創(chuàng)建的對象不能以引用方式賦值給變量
classC{}$c=&newC;
PHP5輸出:
Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3
PHP7輸出:
Parse error: syntax error, unexpected ‘new’ (T_NEW) in /tmp/test.php on line 3
使用類似 ASP 的標簽,以及 script 標簽來區(qū)分 PHP 代碼的方式被移除。 受到影響的標簽有:<% %>、<%= %>、
在不匹配的上下文中以靜態(tài)方式調(diào)用非靜態(tài)方法, 在 PHP 5.6 中已經(jīng)廢棄, 但是在 PHP 7.0 中, 會導(dǎo)致被調(diào)用方法中未定義 $this 變量,以及此行為已經(jīng)廢棄的警告。
classA{publicfunctiontest(){var_dump($this); }}// 注意:并沒有從類 A 繼承classB{publicfunctioncallNonStaticMethodOfA(){A::test(); }}(newB)->callNonStaticMethodOfA();
PHP5輸出:
Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}
PHP7輸出:
Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8
Notice: Undefined variable: this in /tmp/test.php on line 3
NULL
8、在數(shù)值溢出的時候,內(nèi)部函數(shù)將會失敗
將浮點數(shù)轉(zhuǎn)換為整數(shù)的時候,如果浮點數(shù)值太大,導(dǎo)致無法以整數(shù)表達的情況下, 在之前的版本中,內(nèi)部函數(shù)會直接將整數(shù)截斷,并不會引發(fā)錯誤。 在 PHP 7.0 中,如果發(fā)生這種情況,會引發(fā) E_WARNING 錯誤,并且返回 NULL。
JSON 擴展已經(jīng)被 JSOND 擴展取代。
對于數(shù)值的處理,有以下兩點需要注意的:
第一,數(shù)值不能以點號(.)結(jié)束 (例如,數(shù)值 34. 必須寫作 34.0 或 34)。
第二,如果使用科學(xué)計數(shù)法表示數(shù)值,e 前面必須不是點號(.) (例如,3.e3 必須寫作 3.0e3 或 3e3)。
在配置文件INI文件中,不再支持以 # 開始的注釋行, 請使用 ;(分號)來表示注釋。 此變更適用于 php.ini 以及用 parse_ini_file() 和 parse_ini_string() 函數(shù)來處理的文件。
不再提供 $HTTP_RAW_POST_DATA 變量。 請使用 php://input 作為替代。
在使用 yield 關(guān)鍵字的時候,不再需要括號, 并且它變更為右聯(lián)接操作符,其運算符優(yōu)先級介于 print 和 => 之間。 這可能導(dǎo)致現(xiàn)有代碼的行為發(fā)生改變。可以通過使用括號來消除歧義。
echoyield-1;// 在之前版本中會被解釋為:echo(yield) -1;// 現(xiàn)在,它將被解釋為:echoyield(-1);yield$fooordie;// 在之前版本中會被解釋為:yield($fooordie);// 現(xiàn)在,它將被解釋為:(yield$foo)ordie;
mcrypt 擴展已經(jīng)過時了大約10年,并且用起來很復(fù)雜。因此它被廢棄并且被 OpenSSL 所取代。 從PHP 7.2起它將被從核心代碼中移除并且移到PECL中。
2.mb_ereg_replace()和mb_eregi_replace()的Eval選項
對于mb_ereg_replace()和mb_eregi_replace()的 e模式修飾符現(xiàn)在已被廢棄
下面是被棄用或廢除的 INI 指令列表. 使用下面任何指令都將導(dǎo)致 錯誤.
define_syslog_variables
register_globals
register_long_arrays
safe_mode
magic_quotes_gpc
magic_quotes_runtime