简体   繁体   中英

How do I access a property from a class method?

I need to create an instance of a class in my constructor, and then access it in the rest of my methods.

I have tried init function and constructor both, but no luck (as I am new in OOP concepts)

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

}

How can I use $client in my xyz method and other methods in the same class.

Access it via $this->client , like you do in the constructor:

class Foo
{
    private $client;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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