如何从类方法访问属性?

时间:2015-09-08 13:47:12

标签: php

我需要在构造函数中创建一个类的实例,然后在我的其余方法中访问它。

我已尝试init函数和constructor两者,但没有运气(因为我是OOP概念的新手)

private $client;

// first I tried this
public function __construct(){
    $this->client = new \GuzzleHttp\Client();
}

// then I tried this
public function init(){
    $this->client = new \GuzzleHttp\Client();

    // I also tried that
    // $client = new \GuzzleHttp\Client();
}

/**
 * [xyz description]
 * @return [void]
 */
public function xyz(){

    // I need to use that client variable here

}

如何在$client方法和同一类中的其他方法中使用xyz

1 个答案:

答案 0 :(得分:1)

通过$this->client访问它,就像在构造函数中一样:

class Foo
{
    private $client;

    public function __construct()
    {
        $this->client = new \GuzzleHttp\Client();
    }

    public function xyz()
    {
        $this->client->get('...');
    }
}