MySQLi_Result用php>实现Iterator错误5.4

时间:2014-10-22 09:50:23

标签: mysqli iterator

我搜索了很多但没有找到解决方案。

问题:我有一个很好的类,它使用Iterator扩展了MySQLi_Result。所以我可以开箱即用:

$rs = $objConn->rs_query($strSQL);
if ($rs->count() > 0)
{
    foreach ($rs as $user)
    {
        echo $user->$id;
    }
}

并访问其他函数,例如使用$ rs-> key()检索我在foreach期间所在行的偏移量。

rs_query是MySQLi的类扩展,它调用mysqli_real_query并返回MySQL_RS

/ class MySQL

public function rs_query($query)
{
    if (is_string($query) AND empty($query) === FALSE)
    {
        if (!mysqli_real_query($this->link,$query))
        {
            throw new Exception('Error performing query ' . $query . ' Error message :' .mysqli_error($this->link));
            return false;
        }
        else
        {
            return new MySQL_RS($this->link);
        }
    }
}

/ class MySQL_RS

    class MySQL_RS extends MySQLi_Result implements Iterator, Countable
{

    private $_pointer = 0;

    public function movePointer($offset)
    {
        $offset = abs((int)$offset);
        $limit = $this->num_rows - 1;
        if ($limit <= 0 OR $offset > $limit)
        {
            return FALSE;
        }
        unset($limit);
        return $this->data_seek($offset);
    }

    public function count()
    {
        return $this->num_rows;
    }

    public function rewind()
    {
        $this->_pointer = 0;
        $this->data_seek($this->_pointer);
        return $this;
    }

    public function current()
    {
        if (!$this->valid())
        {
            throw new Exception('Unable to retrieve current row.');
        }
        $this->movePointer($this->_pointer);
        return $this->fetchObject();
    }

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

    public function next()
    {
        ++$this->_pointer;
        $this->movePointer($this->_pointer);
        return $this;
    }

    public function valid()
    {
        return $this->_pointer < $this->num_rows;
    }

    public function __destruct()
    {
        $this->close();
    }
}

升级到Php 5.5打破了一切。 Iterator现在已经实现,因此我收到错误

Fatal error: Class MySQL_RS could not implement interface Iterator

但删除

implements Iterator

让我使用foreach访问数据集仅作为关联数组...这可以

$rs = $objConn->rs_query($strSQL);
if ($rs->count() > 0)
{
    foreach ($rs as $user)
    {
        echo $user["id"];
    }
}

或使用while和fetchobject

$rs = $objConn->r_query($strSQL);
if ($rs->count() > 0)
{
    while($user = $rs->fetch_object())
    {
        echo $user->$id
    }
}   

我再也无法访问偏移......

如何在不更改许多不同项目的许多页面中的代码的情况下修复它?

我希望我很清楚,如果我要发布更多信息或代码,我会这样做。

感谢

皮耶罗

0 个答案:

没有答案
相关问题