foreach is the same as the previous array traversal, except that the traversal key is the attribute name and value is the attribute value. When traversing outside the class, you can only traverse to the public attribute, because the others are protected and invisible outside the class.
class HardDiskDrive { public $brand; public $color; public $cpu; public $workState; protected $memory; protected $hardDisk; private $price; public function __construct($brand, $color, $cpu, $workState, $memory, $hardDisk, $price) { $this->brand = $brand; $this->color = $color; $this->cpu = $cpu; $this->workState = $workState; $this->memory = $memory; $this->hardDisk = $hardDisk; $this->price = $price; } } $hardDiskDrive = new HardDiskDrive('Seagate', 'silver', 'tencent', 'well', '1T', 'hard', '$456'); foreach ($hardDiskDrive as $property => $value) { var_dump($property, $value); echo '<br>'; }
The output result is:
string(5) "brand" string(6) "Seagate" string(5) "color" string(6) "silver" string(3) "cpu" string(7) "tencent" string(9) "workState" string(4) "well"
We can also see from the output that regular traversal cannot access the protected properties.
If we want to traverse all the properties of an object, we need to control the behavior of foreach, provide more functions to class objects, and inherit from the interface of Iterator:
This interface implements every operation required by foreach. The execution flow of foreach is as follows:
In the figure example, there are several key steps in foreach: 5.
The five methods of implementation required in Iterator iterator are used to help foreach realize the five key steps of traversing objects:
When foreach traverses the object, if it is found that the object implements the iterator interface, the above five steps are not the default behavior of foreach, but the corresponding method of the object can be called:
Example code:
class Team implements Iterator { //private $name = 'itbsl'; //private $age = 25; //private $hobby = 'fishing'; private $info = ['itbsl', 25, 'fishing']; public function rewind() { reset($this->info); //Reset array pointer } public function valid() { //If it is null, it means there is no element, and return false //Return true if not null return !is_null(key($this->info)); } public function current() { return current($this->info); } public function key() { return key($this->info); } public function next() { return next($this->info); } } $team = new Team(); foreach ($team as $property => $value) { var_dump($property, $value); echo '<br>'; }