Therefore, in order to prevent such information from appearing, when I use foreach, I will force type conversion of the parameters. The situation is as follows:
foreach((array)$arr as $key => $value);
This way Things have been going smoothly, but a few days ago, a problem suddenly occurred. After I cast the type, I can no longer call the object method normally.
Copy code The code is as follows:
class service implements Iterator{
function __construct( $service_define,$filter=null){
$this->iterator = new ArrayIterator($service_define['list']);
$this->filter = $filter;
$this- >valid();
}
function current(){
return $this->current_object;
}
public function rewind() {
$this-> iterator->rewind();
}
public function key() {
return $this->iterator->current();
}
public function next() {
return $this->iterator->next();
}
public function valid() {
while($this->iterator->valid()){
if($this->filter()){
return true;
}else{
$this->iterator->next();
}
};
return false;
}
private function filter(){
$current = $this->iterator->current();
if($current){
$this->current_object = new Sameple($current);
if($this->current_object){
return true;
}
}
return false;
}
}
class Sameple{
var $class_name;
function __construct($class_name = null) {
$this->class_name = $class_name;
}
function show(){
echo $this->class_name,'
';
}
}
$servicelist = array(
'list' = > array(
'first',
'second',
'third',
'fourth',
),
);
$ser = new service ($servicelist);
foreach ($ser as $s) {
$s->show();
}
/*
//The code to execute the error report uses $ser performs cast operation
foreach ((array)$ser as $s) {
$s->show();
}*/
So the problem is that foreach can not only traverse arrays, but also classes that implement the Iterator interface.
I only noticed the situation of arrays before, and ignored the situation of classes that implement the Iterator interface. Will definitely pay attention to it in the future.
Remember in order.
http://www.bkjia.com/PHPjc/322584.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322584.htmlTechArticleSo, in order to prevent such information from appearing, when I use foreach, I will force type conversion of the parameters. As follows: foreach((array)$arr as $key = $value); Do this all the time...