所以,为了防止这样的信息出现,我使用foreach的时候,都会把参数进行强制类型转换,形势如下: foreach((array)$arr as $key => $value); 这样做一直相安无事,就在前几天,突然出现了问题。我强制类型转换以后不能正常的调用object的方法了。 <div class="codetitle"><a style="CURSOR: pointer" data="60430" class="copybut" id="copybut60430" onclick="doCopy('code60430')"> 代码如下:<div class="codebody" id="code60430"> <?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,' '; } } $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接口的类的情况给忽略了。以后一定会注意。 依次为记。 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|