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

大家都知道foreach的参数如果不是数组类型,在运行的时候 就会出现类似“Warning: Invalid argument supplied for foreach() in XXX”warning信息。

所以,为了防止这样的信息出现,我使用foreach的时候,都会把参数进行强制类型转换,形势如下:

foreach((array)$arr as $key => $value);

这样做一直相安无事,就在前几天,突然出现了问题。我强制类型转换以后不能正常的调用object的方法了。

1 <?php
2
3  class service implements Iterator{
4 function __construct($service_define,$filter=null){
5 $this->iterator = new ArrayIterator($service_define['list']);
6 $this->filter = $filter;
7 $this->valid();
8 }
9
10 function current(){
11 return $this->current_object;
12 }
13
14 public function rewind() {
15 $this->iterator->rewind();
16 }
17
18 public function key() {
19 return $this->iterator->current();
20 }
21
22 public function next() {
23 return $this->iterator->next();
24 }
25
26 public function valid() {
27 while($this->iterator->valid()){
28 if($this->filter()){
29 return true;
30 }else{
31 $this->iterator->next();
32 }
33 };
34 return false;
35 }
36
37 private function filter(){
38 $current = $this->iterator->current();
39 if($current){
40 $this->current_object = new Sameple($current);
41 if($this->current_object){
42 return true;
43 }
44 }
45 return false;
46 }
47
48 }
49
50  class Sameple{
51 var $class_name;
52 function __construct($class_name = null) {
53 $this->class_name = $class_name;
54 }
55
56 function show(){
57 echo $this->class_name,'<br />';
58 }
59 }
60
61 $servicelist = array(
62 'list' => array(
63 'first',
64 'second',
65 'third',
66 'fourth',
67 ),
68 );
69 $ser = new service($servicelist);
70 foreach ($ser as $s) {
71 $s->show();
72 }
73 /*
74 //执行报错的代码 使用了将$ser执行强制类型转换操作
75 foreach ((array)$ser as $s) {
76 $s->show();
77 }*/

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

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

依次为记。

原文地址:https://www.cnblogs.com/ainiaa/p/1902044.html