-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectIteration.php
More file actions
34 lines (30 loc) · 1.05 KB
/
Copy pathObjectIteration.php
File metadata and controls
34 lines (30 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
class Data implements IteratorAggregate{
var string $first = "First";
public string $second = "Second";
private string $third = "Third";
protected string $fourth = "Fourth";
public function getIterator(){
/**
* $array = [
* "first" => $this->first,
* //jika kita tidak ingin mengeluarkan data seperti password misal, maka kita bisa tidak tuliskan di iteratornya
* "second" => $this->second,
* "third" => $this->third,
* "fourth" => $this->fourth,
* ];
* return new ArrayIterator($array);
*/
// ini adalah contoh menggunakan kata kunci yield
yield "first" => $this->first;
yield "second" => $this->second;
yield "third" => $this->third;
yield "fourth" => $this->fourth;
}
}
$data = new Data();
// selain foreach bisa digunakan untuk melakukan iterasi dari array
// foreach juga bisa digunakan untuk melakukan iterasi dari object
foreach($data as $key => $value){
echo "$key : $value".PHP_EOL;
}