php foreach 参数强制类型转换的问题

时间:2022-09-25 07:37:28

所以,为了防止这样的信息出现,我使用foreach的时候,都会把参数进行强制类型转换,形势如下: 
foreach((array)$arr as $key => $value); 
这样做一直相安无事,就在前几天,突然出现了问题。我强制类型转换以后不能正常的调用object的方法了。 

复制代码代码如下:


<?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(); 

/* 
//执行报错的代码 使用了将$ser执行强制类型转换操作 
foreach ((array)$ser as $s) { 
$s->show(); 
}*/ 


之所以出现这样的问题就是,foreach不但可以遍历数组,还可以遍历实现了Iterator接口的类。 

我以前只注意到了数组的情况,把实现了Iterator接口的类的情况给忽略了。以后一定会注意。 依次为记。