Home > Backend Development > PHP Tutorial > php foreach 参数强制类型转换的问题_PHP

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

WBOY
Release: 2016-06-01 12:17:53
Original
929 people have browsed it

所以,为了防止这样的信息出现,我使用foreach的时候,都会把参数进行强制类型转换,形势如下:
foreach((array)$arr as $key => $value);
这样做一直相安无事,就在前几天,突然出现了问题。我强制类型转换以后不能正常的调用object的方法了。
复制代码 代码如下:
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接口的类的情况给忽略了。以后一定会注意。
依次为记。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template