PHP Iterables
PHP - Iterable คืออะไร?
iterable คือค่าใด ๆ ที่สามารถวนซ้ำได้ด้วยการforeach()
วนซ้ำ
pseudo-type ถูกนำมา ใช้iterable
ใน PHP 7.1 และสามารถใช้เป็นชนิดข้อมูลสำหรับอาร์กิวเมนต์ของฟังก์ชันและค่าส่งคืนของฟังก์ชัน
PHP - การใช้ Iterables
iterable
คีย์เวิร์ดสามารถใช้เป็นชนิดข้อมูลของอาร์กิวเมนต์ของฟังก์ชันหรือเป็นชนิดส่งคืนของฟังก์ชันได้:
ตัวอย่าง
ใช้อาร์กิวเมนต์ของฟังก์ชัน iterable:
<?php
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
$arr = ["a",
"b", "c"];
printIterable($arr);
?>
ตัวอย่าง
ส่งคืน iterable:
<?php
function getIterable():iterable {
return ["a", "b", "c"];
}
$myIterable = getIterable();
foreach($myIterable as $item) {
echo $item;
}
?>
PHP - การสร้าง Iterables
อาร์เรย์
อาร์เรย์ทั้งหมดเป็นแบบ iterables ดังนั้นอาร์เรย์ใดๆ สามารถใช้เป็นอาร์กิวเมนต์ของฟังก์ชันที่ต้องการ iterable ได้
ตัววนซ้ำ
วัตถุใดๆ ที่ใช้Iterator
อินเทอร์เฟซสามารถใช้เป็นอาร์กิวเมนต์ของฟังก์ชันที่ต้องการ iterable
ตัววนซ้ำประกอบด้วยรายการและจัดเตรียมวิธีการวนซ้ำ มันเก็บตัวชี้ไปยังองค์ประกอบใดองค์ประกอบหนึ่งในรายการ แต่ละรายการในรายการควรมีคีย์ที่สามารถใช้ค้นหารายการได้
ตัววนซ้ำต้องมีวิธีการเหล่านี้:
current()
- ส่งกลับองค์ประกอบที่ตัวชี้กำลังชี้ไป เป็นข้อมูลประเภทใดก็ได้key()
ส่งกลับคีย์ที่เกี่ยวข้องกับองค์ประกอบปัจจุบันในรายการ ต้องเป็นจำนวนเต็ม ทุ่น บูลีน หรือสตริงเท่านั้นnext()
ย้ายตัวชี้ไปยังองค์ประกอบถัดไปในรายการrewind()
ย้ายตัวชี้ไปยังองค์ประกอบแรกในรายการvalid()
หากตัวชี้ภายในไม่ได้ชี้ไปที่องค์ประกอบใด ๆ (เช่น หากมีการเรียก next() ที่ส่วนท้ายของรายการ) สิ่งนี้ควรคืนค่าเป็นเท็จ คืนค่าเป็นจริงในกรณีอื่น ๆ
ตัวอย่าง
ใช้อินเทอร์เฟซ Iterator และใช้เป็น iterable:
<?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);
?>