我试图修改php.net中的示例,试图实现类似Java/C#的集合,其中键可以是对象(http://php.net/manual/en/language.oop5.iterations.php,Example#2):
<?php
class Test {
private $_n;
public function __construct($n) {
$this->_n = $n;
}
public function getN() {
return $this->_n;
}
}
class MyIterator implements Iterator
{
private $var = array();
// code from php.net ....
public function key()
{
$var = key($this->var);
echo "key: $var\n";
return new Test($var);
}
// code from php.net...
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print $a->getN() . ": $b\n";
}
Run Code Online (Sandbox Code Playgroud)
但我有这样的通知:
警告:从MyIterator :: key()返回非法类型
我该怎么解决它?
您正在寻找的东西很容易,但是,您需要帮助foreach一点:
foreach ($it as $b) {
$a = $it->key();
print $a->getN() . ": $b\n";
}
Run Code Online (Sandbox Code Playgroud)
背景:foreach只能处理整数或字符串的键(有些人说标量,我更喜欢数组键类比),但不能处理数组或对象.
然而,手动获取密钥确实可以正常工作,有时甚至需要PHP内置类作为迭代器,但返回一个数组作为键,例如使用MultipleIterator.