您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)如何在PHP7中使用匿名類,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
匿名類跟匿名函數(shù)一樣,創(chuàng)建一次性的簡(jiǎn)單對(duì)象
<?php /** * Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: 00:17 */ echo '匿名函數(shù)'; $anonymous_func = function(){return 'function';}; echo $anonymous_func(); echo '<br>'; echo '<hr>'; class common { public $default = 10; function __construct($key){ $this->getVal($key); } public function getVal(int $i):int{ $this->default += $i; return $this->default+0.1; } } echo '有名函數(shù)';echo '<br>'; $com = new common(1); echo $com->getVal(2.2).'--'; echo $com->getVal(2.2).'--'; echo (new common(1))->getVal(8.9); echo '<hr>';echo '匿名類'; //定義匿名類需繼承 echo (new class(1) extends common{})->getVal(90);echo '<br>'; echo (new class(2) extends common{})->getVal(90);
運(yùn)行效果圖如下:
匿名類被嵌套進(jìn)普通 Class 后,不能訪問這個(gè)外部類(Outer class)的 private(私有)、protected(受保護(hù))方法或者屬性。 為了訪問外部類(Outer class)protected 屬性或方法,匿名類可以 extend(擴(kuò)展)此外部類。 為了使用外部類(Outer class)的 private屬性,必須通過構(gòu)造器傳進(jìn)來:
<?php class Outer { private $prop = 1; protected $prop2 = 2; protected function func1() { return 3; } public function func2() { return new class($this->prop) extends Outer { private $prop3; public function __construct($prop) { $this->prop3 = $prop; } public function func3() { return $this->prop2 + $this->prop3 + $this->func1(); } }; } } echo (new Outer)->func2()->func3();//6
匿名函數(shù)可以實(shí)現(xiàn)閉包,那么相應(yīng)的匿名類也可以實(shí)現(xiàn)閉包
<?php /** * Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: 1:51 */ $arr = array(); for ($i=0; $i<3; $i++){ $arr[] = new class($i){ public $index=0; function __construct($i) { $this->index = $i; echo 'create</br>'; } public function getVal(){ echo $this->index; } }; } $arr[2]->getVal(); echo '<br>'; var_dump($arr[1]);
運(yùn)行效果圖如下:
看完上述內(nèi)容,你們對(duì)如何在PHP7中使用匿名類有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。