PHP OOP从另一个方法调用方法变量

时间:2015-10-29 10:41:59

标签: php function oop methods

我是PHP OOP的新手请耐心地教我。

使用下面的代码,页面将调用" index"要显示的方法。 "索引"想要从另一个方法(getView)调用。

如何纠正" index"的编码方法。

class Report {

    public function index(){
        $over = $this->overview;
        return $over;
    }

    public function getView()
    {
        $overview = 'I want this show up at index';
        return $overview;
    }
}

1 个答案:

答案 0 :(得分:0)

首先,$overview是方法“getView”的局部变量,因此索引方法无法看到它。
只有getView知道它。

其次,您尝试访问$this->overview;,为此,$ overview必须是类Report的属性,因此您的代码应该以:

开头
class Report {

    private $overview;

    public function index(){
        // (your code...)
    }

第三,如果你想让getView和index使用相同的$ overview值,你也必须在getView中使用该属性:

public function getView()
{
    $this->overview = 'I want this show up at index';
    return $this->overview;
}

最后,要查看getView设置的索引,必须确保在index之前调用getView。否则,您必须手动调用它:

class Report {

    private $overview;

    public function index(){
        $this->getView();
        $over = $this->overview;
        // or $over=$this->getView();
        return $over;
    }

    public function getView()
    {
        $this->overview = 'I want this show up at index';
        return $this->overview;
    }