PHP Iterables
PHP - Iterable ဆိုတာဘာလဲ။
iterable သည် foreach()
loop တစ်ခုဖြင့် လှည့်ပတ်နိုင်သည့် မည်သည့်တန်ဖိုးမဆိုဖြစ်သည်။
pseudo-type ကို iterable
PHP 7.1 တွင်မိတ်ဆက်ခဲ့ပြီး၊ ၎င်းကို function arguments နှင့် function return values များအတွက် data type အဖြစ်အသုံးပြုနိုင်ပါသည်။
PHP - Iterables ကိုအသုံးပြုခြင်း။
သော့ချက်စကားလုံးကို လုပ်ဆောင်ချက်အငြင်းအခုံ တစ်ခု၏ iterable
ဒေတာအမျိုးအစားအဖြစ် သို့မဟုတ် လုပ်ဆောင်ချက်တစ်ခု၏ ပြန်ပေးသည့်အမျိုးအစားအဖြစ် အသုံးပြုနိုင်သည်။
ဥပမာ
ထပ်ကာထပ်ကာ လုပ်ဆောင်နိုင်သော အကြောင်းပြချက်ကို အသုံးပြုပါ-
<?php
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
$arr = ["a",
"b", "c"];
printIterable($arr);
?>
ဥပမာ
ထပ်ကာထပ်ကာ ပြန်ပေးပါ။
<?php
function getIterable():iterable {
return ["a", "b", "c"];
}
$myIterable = getIterable();
foreach($myIterable as $item) {
echo $item;
}
?>
PHP - Iterables ဖန်တီးခြင်း။
အခင်းများ
array များအားလုံးသည် iterable များဖြစ်သည်၊ ထို့ကြောင့် မည်သည့် array ကိုမဆို ထပ်၍လုပ်နိုင်သော function လိုအပ်သော array တစ်ခုအဖြစ် သုံးနိုင်သည်။
Iterators
အင်တာဖေ့ စ်ကို အကောင်အထည်ဖော်သည့် မည်သည့်အရာမဆို Iterator
ထပ်ကာထပ်ကာလိုအပ်သည့် လုပ်ဆောင်ချက်တစ်ခု၏ အငြင်းအခုံအဖြစ် အသုံးပြုနိုင်သည်။
iterator တစ်ခုတွင် ပစ္စည်းများစာရင်းပါရှိပြီး ၎င်းတို့ကို လှည့်ပတ်ရန် နည်းလမ်းများကို ပေးသည်။ ၎င်းသည် စာရင်းရှိဒြပ်စင်များအနက်မှ ညွှန်ပြချက်တစ်ခုကို သိမ်းဆည်းထားသည်။ စာရင်းရှိအရာတစ်ခုစီတွင် ဤအရာကိုရှာဖွေရန် အသုံးပြုနိုင်သည့်သော့တစ်ခုရှိသင့်သည်။
ထပ်လောင်းသူသည် ဤနည်းလမ်းများ ရှိရမည်-
current()
- ညွှန်ပြသူသည် လက်ရှိညွှန်ပြနေသည့် အစိတ်အပိုင်းကို ပြန်ပေးသည်။ မည်သည့်ဒေတာအမျိုးအစားဖြစ်နိုင်သည်။key()
စာရင်းရှိ လက်ရှိဒြပ်စင်နှင့် ဆက်စပ်နေသောသော့ကို ပြန်ပေးသည်။ ၎င်းသည် ကိန်းပြည့်၊ float၊ boolean သို့မဟုတ် string တစ်ခုသာ ဖြစ်နိုင်သည်။next()
ညွှန်ပြချက်ကို စာရင်းထဲရှိ နောက်ထပ်ဒြပ်စင်သို့ ရွှေ့ပါ။rewind()
ညွှန်ပြချက်ကို စာရင်းရှိ ပထမဒြပ်စင်သို့ ရွှေ့ပါ။valid()
အတွင်းအမှတ်အသားသည် မည်သည့်ဒြပ်စင်ကိုမျှ မညွှန်ပြပါက (ဥပမာ၊ စာရင်း၏အဆုံးတွင် next() ဟုခေါ်ဆိုပါက) ၎င်းသည် false ပြန်ဖြစ်သင့်သည်။ အခြားမည်သည့်ကိစ္စတွင်မဆို အမှန်အတိုင်းပြန်ဖြစ်နိုင်သည်။
ဥပမာ
Iterator အင်တာဖေ့စ်ကို အကောင်အထည်ဖော်ပြီး ၎င်းကို ထပ်ကာထပ်ကာအဖြစ် အသုံးပြုပါ။
<?php
// Create an Iterator
class MyIterator implements Iterator {
private $items = [];
private $pointer = 0;
public
function __construct($items) {
// array_values() makes
sure that the keys are numbers
$this->items =
array_values($items);
}
public function current() {
return $this->items[$this->pointer];
}
public function
key() {
return $this->pointer;
}
public function next() {
$this->pointer++;
}
public function rewind() {
$this->pointer =
0;
}
public function valid() {
// count() indicates how many items are in the list
return $this->pointer < count($this->items);
}
}
// A
function that uses iterables
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
// Use the iterator as an iterable
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>