PHP foreach parameter casting problem

  • 2020-03-31 21:24:31
  • OfStack

Therefore, to prevent such information from appearing, when I use foreach, I will cast the parameters as follows:
Foreach ((array) $arr as $key = > $value);
This has been doing well, just the other day, suddenly there is a problem. I can't call the object method properly after casting.
 
<?php 
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,'<br />'; 
} 
} 
$servicelist = array( 
'list' => array( 
'first', 
'second', 
'third', 
'fourth', 
), 
); 
$ser = new service($servicelist); 
foreach ($ser as $s) { 
$s->show(); 
} 
/* 
//The code that executes the error report USES $ser to perform a cast operation
foreach ((array)$ser as $s) { 
$s->show(); 
}*/ 

The problem is that foreach can traverse not only groups, but also classes that implement the Iterator interface.

I've only noticed the array case before, ignoring the class that implements the Iterator interface. Be sure to pay attention in the future.
In order.

Related articles: