我尝试修改 php.net 中的示例,以尝试实现类似 Java/C# 的集合,其中键可能是对象(http://php.net/manual/en/language.oop5.iterations.php,示例#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";
}
但我有这样的通知:
警告:从 MyIterator::key() 返回非法类型
我该如何解决?