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/archive/2010/12/10/1902044.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值