欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          深入理解PHP中七個(gè)預(yù)定義接口

          深入理解PHP中七個(gè)預(yù)定義接口

          深入理解預(yù)定義接口

          場景:平常工作中寫的都是業(yè)務(wù)模塊,很少會(huì)去實(shí)現(xiàn)這樣的接口,但是在框架里面用的倒是很多。

          1. Traversable(遍歷)接口

          該接口不能被類直接實(shí)現(xiàn),如果直接寫了一個(gè)普通類實(shí)現(xiàn)了該遍歷接口,是會(huì)直接報(bào)致命的錯(cuò)誤,提示使用 Iterator(迭代器接口)或者 IteratorAggregate(聚合迭代器接口)來實(shí)現(xiàn),這兩個(gè)接口后面會(huì)介紹;所有通常情況下,我們只是會(huì)用來判斷該類是否可以使用 foreach 來進(jìn)行遍歷;

          class Test implements Traversable     {     }     上面這個(gè)是錯(cuò)誤示范,該代碼會(huì)提示這樣的錯(cuò)誤:     Fatal error: Class Test must implement interface Traversable as part of either Iterator or      IteratorAggregate in Unknown on line 0

          上面的大致意思是說如要實(shí)現(xiàn)這個(gè)接口,必須同Iterator或者IteratorAggregate來實(shí)現(xiàn)

          正確的做法:

          當(dāng)我們要判斷一個(gè)類是否可以使用foreach來進(jìn)行遍歷,只需要判斷是否是traversable的實(shí)例

               class Test      {      }      $test = new Test;      var_dump($test instanceOf Traversable);

          2. Iterator(迭代器)接口

          迭代器接口其實(shí)實(shí)現(xiàn)的原理就是類似指針的移動(dòng),當(dāng)我們寫一個(gè)類的時(shí)候,通過實(shí)現(xiàn)對(duì)應(yīng)的 5 個(gè)方法:key(),current(),next(),rewind(),valid(),就可以實(shí)現(xiàn)數(shù)據(jù)的迭代移動(dòng),具體看以下代碼

          <?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

          看了這個(gè)原理我們就知道,其實(shí)迭代的移動(dòng)方式:rewind()-> valid()->key() -> current() -> next() -> valid()-> key() ….-> valid();

          好的,理解了上面,我們打開Iterator的接口,發(fā)現(xiàn)它是實(shí)現(xiàn)了Traversable(遍歷)接口的,接下來我們來證明下:

          var_dump($test instanceOf Traversable);

          結(jié)果返回的是true,證明這個(gè)類的對(duì)象是可以進(jìn)行遍歷的。

           foreach ($test as $key => $value){          echo $test->key . ':' . $test->current() . PHP_EOL;   }

          這個(gè)的結(jié)果跟while循環(huán)實(shí)現(xiàn)的模式是一樣的。

          3. IteratorAggregate(聚合迭代器) 接口

          聚合迭代器和迭代器的原理是一樣的,只不過聚合迭代器已經(jīng)實(shí)現(xiàn)了迭代器原理,你只需要實(shí)現(xiàn)一個(gè) getIterator()方法來實(shí)現(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類的對(duì)象傳進(jìn)去當(dāng)做迭代器,通過while循環(huán)的話,我們必須通過調(diào)用getIterator()方法獲取到迭代器對(duì)象,然后直接進(jìn)行迭代輸出,而不需要去實(shí)現(xiàn)相關(guān)的key()等方法。     當(dāng)然這個(gè)時(shí)候,我們肯定想知道是否可以直接從foreach進(jìn)行迭代循環(huán)出去呢?那么我們來打印一下結(jié)果      $test = new Test;     var_dump($test instanceOf Traversable);      結(jié)果是輸出bool true,所以我們接下來是直接用foreach來實(shí)現(xiàn)一下。      $test = new Test;   foreach($test as $key => $value) {      echo $key . ' : ' . $value  .  PHP_EOL;   }   接下來,我們看到是對(duì)對(duì)象進(jìn)行迭代,這個(gè)時(shí)候我們是否可以數(shù)組進(jìn)行迭代呢?   class Test implements IteratorAggregate  {     public $data;      public function __construct()     {         $this->data = [''one' =>  1 , 'two' => 2];     }      public function getIterator()     {         return new AraayIterator($this->data);     }  }   同理實(shí)現(xiàn)的方式跟對(duì)對(duì)象進(jìn)行迭代是一樣的。

          很多PHPer在進(jìn)階的時(shí)候總會(huì)遇到一些問題和瓶頸,業(yè)務(wù)代碼寫多了沒有方向感,不知道該從那里入手去提升,對(duì)此我整理了一些資料,包括但不限于:分布式架構(gòu)、高可擴(kuò)展、高性能、高并發(fā)、服務(wù)器性能調(diào)優(yōu)、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優(yōu)化、shell腳本、Docker、微服務(wù)、Nginx等多個(gè)知識(shí)點(diǎn)高級(jí)進(jìn)階干貨需要的可以免費(fèi)分享給大家,需要的加群(點(diǎn)擊→)677079770

          4. ArrayAccess(數(shù)組式訪問)接口

          通常情況下,我們會(huì)看到 this ['name'] 這樣的用法,但是我們知道,$this 是一個(gè)對(duì)象,是如何使用數(shù)組方式訪問的?答案就是實(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]);     當(dāng)然我們也有經(jīng)典的一個(gè)做法就是把對(duì)象的屬性當(dā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 (序列化)接口

          通常情況下,如果我們的類中定義了魔術(shù)方法,sleep(),wakeup () 的話,我們?cè)谶M(jìn)行 serialize () 的時(shí)候,會(huì)先調(diào)用 sleep () 的魔術(shù)方法,我們通過返回一個(gè)數(shù)組,來定義對(duì)對(duì)象的哪些屬性進(jìn)行序列化,同理,我們?cè)谡{(diào)用反序列化 unserialize () 方法的時(shí)候,也會(huì)先調(diào)用的 wakeup()魔術(shù)方法,我們可以進(jìn)行初始化,如對(duì)一個(gè)對(duì)象的屬性進(jìn)行賦值等操作;但是如果該類實(shí)現(xiàn)了序列化接口,我們就必須實(shí)現(xiàn) serialize()方法和 unserialize () 方法,同時(shí) sleep()和 wakeup () 兩個(gè)魔術(shù)方法都會(huì)同時(shí)不再支持,具體代碼看如下;

          <?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));      //實(shí)現(xiàn)序列化接口,發(fā)現(xiàn)魔術(shù)方法失效了     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ù)其實(shí)返回的都是 Closure 閉包類的一個(gè)實(shí)例,該類中主要有兩個(gè)方法,bindTo()和 bind(),通過查看源碼,可以發(fā)現(xiàn)兩個(gè)方法是殊途同歸,只不過是 bind () 是個(gè)靜態(tài)方法,具體用法看如下;

          <?php     $closure = function () {         return 'hello world';     }      var_dump($closure);     var_dump($closure());

          通過上面的例子,可以看出第一個(gè)打印出來的是 Closure 的一個(gè)實(shí)例,而第二個(gè)就是打印出匿名函數(shù)返回的 hello world 字符串;接下來是使用這個(gè)匿名類的方法,這兩個(gè)方法的目的都是把匿名函數(shù)綁定一個(gè)類上使用;

          bindTo()

          <?php namespace demo1;     class Test {         private $name = 'hello woeld';     }      $closure = function () {         return $this->name;     }      $func = $closure->bindTo(new Test);     $func();     // 這個(gè)是可以訪問不到私有屬性的,會(huì)報(bào)出無法訪問私有屬性     // 下面這個(gè)是正確的做法     $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 實(shí)現(xiàn)了 Iterator,但是他無法被繼承,同時(shí)也生成實(shí)例。既然實(shí)現(xiàn)了 Iterator,所以正如上文所介紹,他也就有了和 Iterator 相同的功能:rewind->valid->current->key->next…,Generator 的語法主要來自于關(guān)鍵字 yield。yield 就好比一次循環(huán)的中轉(zhuǎn)站,記錄本次的活動(dòng)軌跡,返回一個(gè) Generator 的實(shí)例。

          Generator 的優(yōu)點(diǎn)在于,當(dāng)我們要使用到大數(shù)據(jù)的遍歷,或者說大文件的讀寫,而我們的內(nèi)存不夠的情況下,能夠極大的減少我們對(duì)于內(nèi)存的消耗,因?yàn)閭鹘y(tǒng)的遍歷會(huì)返回所有的數(shù)據(jù),這個(gè)數(shù)據(jù)存在內(nèi)存上,而 yield 只會(huì)返回當(dāng)前的值,不過當(dāng)我們?cè)谑褂?yield 時(shí),其實(shí)其中會(huì)有一個(gè)處理記憶體的過程,所以實(shí)際上這是一個(gè)用時(shí)間換空間的辦法。

          <?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

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)