简体   繁体   English

尝试了解php中的Iterator接口

[英]try to understand The Iterator interface in php

I am reading http://php.net/manual/en/class.iterator.php , but had a hard time to understand the Example #1 Basic usage. 我正在阅读http://php.net/manual/en/class.iterator.php ,但很难理解Example#1 Basic的用法。 Questions: 问题:

  1. var_dump(__METHOD__);

    I know you can use variable here, eg: var_dump($count) , but METHOD is not variable, or it is global variable/constant? 我知道你可以在这里使用变量,例如: var_dump($count) ,但METHOD不是变量,还是全局变量/常量?

  2.  foreach($it as $key => $value) { var_dump($key, $value); echo "\\n"; } 

    if I change it to: 如果我改为:

     foreach($it as $key => $value) { } 

    if I run the script, it can still show the outcome, why? 如果我运行脚本,它仍然可以显示结果,为什么?

  3. var_dump($key, $value);

    the outcome is 结果是

    int 0 string 'firstelement' (length=12) int 0 string'firstelement'(长度= 12)

    int 1 string 'secondelement' (length=13) ... int 1字符串'secondelement'(长度= 13)...

    why it is this result? 为什么会出现这种结果? foreach($it as $key => $value) , $it is object, it is not $array, so how could this happen? foreach($it as $key => $value) ,$它是对象,它不是$ array,所以怎么会发生这种情况?

The Iterator interface allows the class to behave like it was an array in the foreach statement. Iterator接口允许类的行为类似于foreach语句中的数组。

Because it's not an array, the class must know, how to behave in this situation. 因为它不是一个数组,所以该类必须知道如何在这种情况下表现。 This is done by calling (by the foreach , let's say for simplicity) some methods that are implemented from the Iterator interface. 这是通过调用(由foreach ,为简单起见)来完成从Iterator接口实现的一些方法。 As it's the interface requirements, all of the methods should be implemented, even if you're not going to use some of them, like retrieving the key. 由于它是接口要求,所以应该实现所有方法,即使您不打算使用其中一些方法,例如检索密钥。

In the methods you can type whatever you like, even something that does not makes sense in the foreach loop (say you do not increase the counter $position ). 在这些方法中,您可以键入任何您喜欢的内容,即使是在foreach循环中没有意义的内容(假设您不增加计数器$position )。

In the manual the var_dump() s are used to show you which methods are called. 在手册中, var_dump()用于显示调用哪些方法。 The __METHOD__ pseudo-constant is a string that returns the current method's name. __METHOD__伪常量是一个返回当前方法名称的字符串。 You should remove these lines, as they are given for the example purposes only. 您应该删除这些行,因为它们仅用于示例目的。

Each of the methods from the Iterator interface are public, so you can call them from any place in the code, but there is no need to call them in your program. Iterator接口中的每个方法都是公共的,因此您可以从代码中的任何位置调用它们,但不需要在程序中调用它们。 In the foreach loop they are called automatically so that's why your empty loop works. foreach循环中,它们会被自动调用,这就是你的空循环工作的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM