PHP Generator::valid() 方法

返回上一级

PHP Generator::valid() 方法返回迭代器是否已经关闭 ( 已经迭代完毕 )。

( PHP 5 >= 5.5.0, PHP 7 )

方法原型

PHP Generator::valid() 方法的原型如下

public bool Generator::valid ( void )

调用该方法不用传递任何参数。

该方法会返回一个 boolean 值用于表示生成器是否关闭。如果返回 FALSE 则表示已经关闭,否则返回 TRUE

范例

我们写一个范例演示下 valid() 方法。

这个演示示例其实没有任何实际意义,因为 foreach 循环语句默认会自动调用该方法

<?php

function gen_zero_to_ten() {
    for ($i = 1; $i <= 10; $i++) {
        yield $i;
    }
}

$generator = gen_zero_to_ten();
foreach ($generator as $key => $value) {
    echo $key ," => ", $value, "\n";
    echo "is closed:", intval($generator->valid()),"\n";
}

echo "after foreach, is closed: ", intval($generator->valid()),"\n";

运行结果如下

0 => 1
is closed:1
1 => 2
is closed:1
2 => 3
is closed:1
3 => 4
is closed:1
4 => 5
is closed:1
5 => 6
is closed:1
6 => 7
is closed:1
7 => 8
is closed:1
8 => 9
is closed:1
9 => 10
is closed:1
after foreach, is closed: 0

返回上一级

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.