学习php oop - 无法反转数组

时间:2011-03-02 12:56:45

标签: php oop

我正在学习PHP OOP,我试图理解为什么以下脚本不起作用:

class ShowTimeline {
    var $conn;
    var $rev;

    function getTimeline ($conn) {
        return $this->conn;
    }

    function reverseTimeline () {
        $rev = array_reverse($this->conn, false);
        return $rev;
    }

    function display () {
        $this->reverseTimeline();
        print_r($this->rev);
    }
}
print '<hr />';
$connect = new showTimeline();
$connect->conn = array('one', 'two', 'three');
$connect->display();

当我将脚本更改为:

//same stuff above
function display () {
            $this->reverseTimeline();
            print_r($this->conn); //changed from $this->rev
        }
//same stuff below

我打印出来了:

Array ( [0] => one [1] => two [2] => three )

这是正确的。请帮帮忙?

3 个答案:

答案 0 :(得分:6)

使用$this->访问类'参数。

function reverseTimeline () {
    $this->rev = array_reverse($this->conn, false);
    return $this->rev;
}

仅使用$rev将其视为局部变量。

答案 1 :(得分:1)

当您分配到$rev时,您实际上是在分配一个局部变量,而不是对象中的$rev$this->rev永远不会被设定。

将您的$rev更改为$this->rev,事情就应该开始了。

答案 2 :(得分:0)

你实际上从未将$ this-&gt; rev设置为反向数组。

function reverseTimeline () {
            $rev = array_reverse($this->conn, false);
            $this->rev = $rev;
       }

function display () {
            $this->reverseTimeline();
            print_r($this->rev);
        }

会这样做。