简体   繁体   English

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

[英]PHP OOP call method variable from another method

I'm newbie at PHP OOP please patient to teach me. 我是PHP OOP的新手,请耐心教我。

With the code below, the page will call "index" method to be shown. 使用下面的代码,页面将调用“ index”方法来显示。 And the "index" method wants to call from another method (getView). 而且“索引”方法要从另一个方法(getView)调用。

How to correct the code method of "index". 如何更正“索引”的编码方法。

class Report {

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

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

First, $overview is a local variable of the method "getView", so the index method can't see it. 首先, $overview是方法“ getView”的局部变量,因此索引方法看不到它。
Only getView knows it. 只有getView知道。

Second, you try to access $this->overview; 其次,您尝试访问$this->overview; , to do that, $overview must be attribute of the class Report, so your code should start with : ,为此,$ overview必须是Report类的属性,因此您的代码应以:

class Report {

    private $overview;

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

Third, if you want getView and index to use the same value of $overview, you have to use the attribute in getView too : 第三,如果要让getView和index使用相同的$ overview值,则也必须在getView中使用该属性:

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

Finally, for index to see the value set by getView, you have to be sure that getView is called before index. 最后,为了使index查看由getView设置的值,必须确保在index之前调用了getView。 Otherwise, you have to call it manually : 否则,您必须手动调用它:

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM