久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      深入理解PHP中七個預定義接口

      深入理解PHP中七個預定義接口

      深入理解預定義接口

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

      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)相關(guā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)的方式跟對對象進行迭代是一樣的。

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

      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 (序列化)接口

      通常情況下,如果我們的類中定義了魔術(shù)方法,sleep(),wakeup () 的話,我們在進行 serialize () 的時候,會先調(diào)用 sleep () 的魔術(shù)方法,我們通過返回一個數(shù)組,來定義對對象的哪些屬性進行序列化,同理,我們在調(diào)用反序列化 unserialize () 方法的時候,也會先調(diào)用的 wakeup()魔術(shù)方法,我們可以進行初始化,如對一個對象的屬性進行賦值等操作;但是如果該類實現(xiàn)了序列化接口,我們就必須實現(xiàn) serialize()方法和 unserialize () 方法,同時 sleep()和 wakeup () 兩個魔術(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));      //實現(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ù)其實返回的都是 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 的語法主要來自于關(guān)鍵字 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

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