[英]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) 我尝试了
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
}
How can I use $client
in my xyz
method and other methods in the same class. 如何在
xyz
方法和同一类中的其他方法中使用$client
。
Access it via $this->client
, like you do in the constructor: 通过
$this->client
访问它,就像在构造函数中一样:
class Foo
{
private $client;
public function __construct()
{
$this->client = new \GuzzleHttp\Client();
}
public function xyz()
{
$this->client->get('...');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.