English | 简体中文 | 繁體中文
查询

ReflectionClass::isIterateable()函数—用法及示例

「 检查类是否实现了可迭代接口 」


函数名:ReflectionClass::isIterateable() 

适用版本:PHP 7.1.0及以上

函数描述: ReflectionClass::isIterateable() 方法用于检查类是否实现了可迭代接口。如果类实现了 Traversable 接口,或者实现了一个可以用 foreach 进行迭代的公共方法,则返回 true,否则返回 false。

用法示例:

class MyIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "firstElement",
        "secondElement",
        "thirdElement",
    );

    public function __construct() {
        $this->position = 0;
    }

    public function rewind() {
        $this->position = 0;
    }

    public function current() {
        return $this->array[$this->position];
    }

    public function key() {
        return $this->position;
    }

    public function next() {
        ++$this->position;
    }

    public function valid() {
        return isset($this->array[$this->position]);
    }
}

$reflection = new ReflectionClass('MyIterator');
$isIterable = $reflection->isIterateable();

if ($isIterable) {
    echo "MyIterator is iterable.";
} else {
    echo "MyIterator is not iterable.";
}

上述示例中,我们定义了一个类 MyIterator,实现了 Iterator 接口的方法。然后我们使用 ReflectionClass 创建了一个 MyIterator 类的反射对象,并使用 ReflectionClass::isIterateable() 方法检查该类是否可迭代。根据返回值,我们输出对应的结果。

在这个例子中,MyIterator 类实现了 Iterator 接口的所有方法,因此 ReflectionClass::isIterateable() 方法会返回 true,最后输出 "MyIterator is iterable."。

补充纠错
热门PHP函数
分享链接