目錄
- 1. Traversable(遍歷)接口
- 2. Iterator(迭代器)接口
- 3. IteratorAggregate(聚合迭代器) 接口
- 4.ArrayAccess(數(shù)組式訪問)接口
- 5. Serializable (序列化)接口
- 6. Closure 類
- 7. Generator (生成器)
1. Traversable(遍歷)接口
該接口不能被類直接實現(xiàn),如果直接寫了一個普通類實現(xiàn)了該遍歷接口,是會直接報致命的錯誤,提示使用 Iterator(迭代器接口)或者 IteratorAggregate(聚合迭代器接口)來實現(xiàn),這兩個接口后面會介紹;所有通常情況下,我們只是會用來判斷該類是否可以使用 foreach 來進行遍歷;
class Test implements Traversable
{
}
上面這個是錯誤示范,該代碼會提示這樣的錯誤:
Fatal error: Class Test must implement interface Traversable as part of either Iterator or
IteratorAggregate in Unknown on line 0
上面的大致意思是說如要實現(xiàn)這個接口,必須同Iterator或者IteratorAggregate來實現(xiàn) 正確的做法: 當我們要判斷一個類是否可以使用foreach來進行遍歷,只需要判斷是否是traversable的實例
class Test
{
}
$test = new Test;
var_dump($test instanceOf Traversable);
2. Iterator(迭代器)接口
迭代器接口其實實現(xiàn)的原理就是類似指針的移動,當我們寫一個類的時候,通過實現(xiàn)對應的 5 個方法:key(),current(),next(),rewind(),valid(),就可以實現(xiàn)數(shù)據(jù)的迭代移動,具體看以下代碼
?php
class Test implements Iterator
{
private $key;
private $val = [
'one',
'two',
'three',
];
public function key()
{
return $this->key;
}
public function current()
{
return $this->val[$this->key];
}
public function next()
{
++$this->key;
}
public function rewind()
{
$this->key = 0;
}
public function valid()
{
return isset($this->val[$this->key]);
}
}
$test = new Test;
$test->rewind();
while($test->valid()) {
echo $test->key . ':' . $test->current() . PHP_EOL;
$test->next();
}
## 該輸出結(jié)果 :
0: one
1: two
2: three
看了這個原理我們就知道,其實迭代的移動方式:rewind()-> valid()->key() -> current() -> next() -> valid()-> key() ....-> valid();
好的,理解了上面,我們打開Iterator的接口,發(fā)現(xiàn)它是實現(xiàn)了Traversable(遍歷)接口的,接下來我們來證明下:
var_dump($test instanceOf Traversable);
結(jié)果返回的是true,證明這個類的對象是可以進行遍歷的。
foreach ($test as $key => $value){
echo $test->key . ':' . $test->current() . PHP_EOL;
}
這個的結(jié)果跟while循環(huán)實現(xiàn)的模式是一樣的。
3. IteratorAggregate(聚合迭代器) 接口
聚合迭代器和迭代器的原理是一樣的,只不過聚合迭代器已經(jīng)實現(xiàn)了迭代器原理,你只需要實現(xiàn)一個 getIterator()方法來實現(xiàn)迭代,具體看以下代碼
?php
class Test implements IteratorAggregate
{
public $one = 1;
public $two = 2;
public $three = 3;
public function __construct()
{
$this->four = 4;
}
public function getIterator()
{
return new AraayIterator($this);
}
}
$test = (new Test())->getIterator();
$test->rewind();
while($test->valid()) {
echo $test->key() . ' : ' . $test->current() . PHP_EOL;
$test->next();
}
//從上面的代碼,我們可以看到我們將Test類的對象傳進去當做迭代器,通過while循環(huán)的話,我們必須通過調(diào)用getIterator()方法獲取到迭代器對象,然后直接進行迭代輸出,而不需要去實現(xiàn)相關的key()等方法。
//當然這個時候,我們肯定想知道是否可以直接從foreach進行迭代循環(huán)出去呢?那么我們來打印一下結(jié)果
$test = new Test;
var_dump($test instanceOf Traversable);
//結(jié)果是輸出bool true,所以我們接下來是直接用foreach來實現(xiàn)一下。
$test = new Test;
foreach($test as $key => $value) {
echo $key . ' : ' . $value . PHP_EOL;
}
//接下來,我們看到是對對象進行迭代,這個時候我們是否可以數(shù)組進行迭代呢?
class Test implements IteratorAggregate
{
public $data;
public function __construct()
{
$this->data = [''one' => 1 , 'two' => 2];
}
public function getIterator()
{
return new AraayIterator($this->data);
}
}
//同理實現(xiàn)的方式跟對對象進行迭代是一樣的。
4.ArrayAccess(數(shù)組式訪問)接口
通常情況下,我們會看到 this ['name'] 這樣的用法,但是我們知道,$this 是一個對象,是如何使用數(shù)組方式訪問的?答案就是實現(xiàn)了數(shù)據(jù)組訪問接口 ArrayAccess,具體代碼如下
?php
class Test implements ArrayAccess
{
public $container;
public function __construct()
{
$this->container = [
'one' => 1,
'two' => 2,
'three' => 3,
];
}
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
}
$test = new Test;
var_dump(isset($test['one']));
var_dump($test['two']);
unset($test['two']);
var_dump(isset($test['two']));
$test['two'] = 22;
var_dump($test['two']);
$test[] = 4;
var_dump($test);
var_dump($test[0]);
//當然我們也有經(jīng)典的一個做法就是把對象的屬性當做數(shù)組來訪問
class Test implements ArrayAccess
{
public $name;
public function __construct()
{
$this->name = 'gabe';
}
public function offsetExists($offset)
{
return isset($this->$offset);
}
public function offsetGet($offset)
{
return isset($this->$offset) ? $this->$offset : null;
}
public function offsetSet($offset, $value)
{
$this->$offset = $value;
}
public function offsetUnset($offset)
{
unset($this->$offset);
}
}
$test = new Test;
var_dump(isset($test['name']));
var_dump($test['name']);
var_dump($test['age']);
$test[1] = '22';
var_dump($test);
unset($test['name']);
var_dump(isset($test['name']));
var_dump($test);
$test[] = 'hello world';
var_dump($test);
5. Serializable (序列化)接口
通常情況下,如果我們的類中定義了魔術方法,sleep(),wakeup () 的話,我們在進行 serialize () 的時候,會先調(diào)用sleep () 的魔術方法,我們通過返回一個數(shù)組,來定義對對象的哪些屬性進行序列化,同理,我們在調(diào)用反序列化 unserialize () 方法的時候,也會先調(diào)用的wakeup()魔術方法,我們可以進行初始化,如對一個對象的屬性進行賦值等操作;但是如果該類實現(xiàn)了序列化接口,我們就必須實現(xiàn) serialize()方法和 unserialize () 方法,同時sleep()和wakeup () 兩個魔術方法都會同時不再支持,具體代碼看如下;
?php
class Test
{
public $name;
public $age;
public function __construct()
{
$this->name = 'gabe';
$this->age = 25;
}
public function __wakeup()
{
var_dump(__METHOD__);
$this->age++;
}
public function __sleep()
{
var_dump(__METHOD__);
return ['name'];
}
}
$test = new Test;
$a = serialize($test);
var_dump($a);
var_dump(unserialize($a));
//實現(xiàn)序列化接口,發(fā)現(xiàn)魔術方法失效了
class Test implements Serializable
{
public $name;
public $age;
public function __construct()
{
$this->name = 'gabe';
$this->age = 25;
}
public function __wakeup()
{
var_dump(__METHOD__);
$this->age++;
}
public function __sleep()
{
var_dump(__METHOD__);
return ['name'];
}
public function serialize()
{
return serialize($this->name);
}
public function unserialize($serialized)
{
$this->name = unserialize($serialized);
$this->age = 1;
}
}
$test = new Test;
$a = serialize($test);
var_dump($a);
var_dump(unserialize($a));
6. Closure 類
用于代表匿名函數(shù)的類,凡是匿名函數(shù)其實返回的都是 Closure 閉包類的一個實例,該類中主要有兩個方法,bindTo()和 bind(),通過查看源碼,可以發(fā)現(xiàn)兩個方法是殊途同歸,只不過是 bind () 是個靜態(tài)方法,具體用法看如下;
?php
$closure = function () {
return 'hello world';
}
var_dump($closure);
var_dump($closure());
通過上面的例子,可以看出第一個打印出來的是 Closure 的一個實例,而第二個就是打印出匿名函數(shù)返回的 hello world 字符串;接下來是使用這個匿名類的方法,這兩個方法的目的都是把匿名函數(shù)綁定一個類上使用;
bindTo()
?php
namespace demo1;
class Test {
private $name = 'hello woeld';
}
$closure = function () {
return $this->name;
}
$func = $closure->bindTo(new Test);
$func();
// 這個是可以訪問不到私有屬性的,會報出無法訪問私有屬性
// 下面這個是正確的做法
$func = $closure->bindTo(new Test, Test::class);
$func();
namespace demo2;
class Test
{
private statis $name = 'hello world';
}
$closure = function () {
return self::$name;
}
$func = $closure->bindTo(null, Test::class);
$func();
bind()
?php
namespace demo1;
class Test
{
private $name = 'hello world';
}
$func = \Closure::bind(function() {
return $this->name;
}, new Test, Test::class);
$func();
namespace demo2;
class Test
{
private static $name = 'hello world';
}
$func = \Closure::bind(function() {
return self::$name;
}, null, Test::class);
$func()
7. Generator (生成器)
Generator 實現(xiàn)了 Iterator,但是他無法被繼承,同時也生成實例。既然實現(xiàn)了 Iterator,所以正如上文所介紹,他也就有了和 Iterator 相同的功能:rewind->valid->current->key->next...,Generator 的語法主要來自于關鍵字 yield。yield 就好比一次循環(huán)的中轉(zhuǎn)站,記錄本次的活動軌跡,返回一個 Generator 的實例。Generator 的優(yōu)點在于,當我們要使用到大數(shù)據(jù)的遍歷,或者說大文件的讀寫,而我們的內(nèi)存不夠的情況下,能夠極大的減少我們對于內(nèi)存的消耗,因為傳統(tǒng)的遍歷會返回所有的數(shù)據(jù),這個數(shù)據(jù)存在內(nèi)存上,而 yield 只會返回當前的值,不過當我們在使用 yield 時,其實其中會有一個處理記憶體的過程,所以實際上這是一個用時間換空間的辦法。
?php
$start_time = microtime(true);
function xrange(int $num){
for($i = 0; $i $num; $i++) {
yield $i;
}
}
$generator = xrange(100000);
foreach ($generator as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
echo 'memory: ' . memory_get_usage() . ' time: '. (microtime(true) - $start_time);
輸出:
memory: 388904 time: 0.12135100364685
?php
$start_time = microtime(true);
function xrange(int $num){
$arr = [];
for($i = 0; $i $num; $i++) {
array_push($arr, $i);
}
return $arr;
}
$arr = xrange(100000);
foreach ($arr as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
echo 'memory: ' . memory_get_usage() . ' time: '. (microtime(true) - $start_time);
輸出:
memory: 6680312 time: 0.10804104804993
以上就是詳解PHP的7個預定義接口的詳細內(nèi)容,更多關于PHP的7個預定義接口的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- 如何理解PHP程序執(zhí)行的過程原理
- 如何使用PHP依賴管理工具Composer
- 如何使用Casbin作為ThinkPHP的權限控制中間件
- 詳解php內(nèi)存管理機制與垃圾回收機制
- 淺談PHP性能優(yōu)化之php.ini配置
- 如何使用Zephir輕松構建PHP擴展
- 如何讓PHP的代碼更安全
- 詳解thinkphp的Auth類認證
- 如何使用PHP7的Yaconf