《PHP學(xué)習(xí):PHP7匿名類(lèi)用法分析》要點(diǎn):
本文介紹了PHP學(xué)習(xí):PHP7匿名類(lèi)用法分析,希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
PHP學(xué)習(xí)本文實(shí)例講述了PHP7匿名類(lèi)用法.分享給大家供大家參考,具體如下:
PHP學(xué)習(xí)匿名類(lèi)跟匿名函數(shù)一樣,創(chuàng)建一次性的簡(jiǎn)單對(duì)象
PHP學(xué)習(xí)
<?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 '匿名類(lèi)';
//定義匿名類(lèi)需繼承
echo (new class(1) extends common{})->getVal(90);echo '<br>';
echo (new class(2) extends common{})->getVal(90);
PHP學(xué)習(xí)運(yùn)行效果圖如下:
PHP學(xué)習(xí)
PHP學(xué)習(xí)匿名類(lèi)被嵌套進(jìn)普通 Class 后,不能訪(fǎng)問(wèn)這個(gè)外部類(lèi)(Outer class)的 private(私有)、protected(受保護(hù))方法或者屬性. 為了訪(fǎng)問(wèn)外部類(lèi)(Outer class)protected 屬性或方法,匿名類(lèi)可以 extend(擴(kuò)展)此外部類(lèi). 為了使用外部類(lèi)(Outer class)的 private屬性,必須通過(guò)構(gòu)造器傳進(jìn)來(lái):
PHP學(xué)習(xí)
<?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
PHP學(xué)習(xí)匿名函數(shù)可以實(shí)現(xiàn)閉包,那么相應(yīng)的匿名類(lèi)也可以實(shí)現(xiàn)閉包
PHP學(xué)習(xí)
<?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]);
PHP學(xué)習(xí)運(yùn)行效果圖如下:
PHP學(xué)習(xí)
PHP學(xué)習(xí)更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《PHP基本語(yǔ)法入門(mén)教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
PHP學(xué)習(xí)希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助.
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.snjht.com/jiaocheng/3202.html