我正在学习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 )
这是正确的。请帮帮忙?
答案 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);
}
会这样做。