类中的变量null

时间:2017-06-12 18:09:53

标签: php dependencies

这是我的代码:

// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;

$sid = '***';
$token = '***';
$client = new Client($sid, $token);

class TextMessage {

    function sendTextMessage() {

        $client->messages->create(
            '+10000000000',
            array(
                'from' => '+1123456790',
                'body' => 'Hello, this is just a test text message'
                )
            );

    }

}

我收到错误:

  

PHP致命错误:未捕获错误:在

中调用null上的成员函数create()

如何解决这个问题而不使用全局?谢谢!

1 个答案:

答案 0 :(得分:2)

$client为空,因为它在sendTextMessage方法范围内未定义。

向您的类添加构造函数方法并注入客户端。然后使用$this->client代替$client

class TextMessage {

    function __construct($client) {
        $this->client = $client;
    }

    function sendTextMessage() {

        $this->client->messages->create(
            '+10000000000',
            array(
                'from' => '+1123456790',
                'body' => 'Hello, this is just a test text message'
                )
            );

    }

}

$client = new Client($sid, $token);
$textMessage = new TextMessage($client);

OR

将客户端作为参数传递给sentTextMessage方法。

class TextMessage {

    function sendTextMessage($client) {

        $client->messages->create(
            '+10000000000',
            array(
                'from' => '+1123456790',
                'body' => 'Hello, this is just a test text message'
                )
            );

    }

}

$client = new Client($sid, $token);
$textMessage = new TextMessage;
$textMessage->setTextMessage($client);