dro80463 2018-10-27 07:55
浏览 142
已采纳

使用Guzzle 6使用REST API

I try to consume REST API using Guzzle 6. I read the documentation of Guzzle and I got way to consume REST API like below :

<?php

class Index extends CI_Controller {

    use GuzzleHttp\Client;

    $client = new Client([    
        'base_uri' => 'https://api.rajaongkir.com/basic/'
    ]); //LINE ERROR

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    function index() {
        // $client = new GuzzleHttp\Client(['base_uri' => 'https://api.rajaongkir.com/basic/']);
        $key = "b5231ee43b8ee75764bd6a289c4c576d";
        $response = $client->request('GET','province?key='.$key);
        $data['data'] = json_decode($response->getBody());
        $this->load->view('index', $data);
    }
}

If I declare variable $client in function index() there is no problem. I get the JSON and I success to show in my view. I want just once declare base uri and key and I can use the base uri and key to all function I have.

So I try to declare variable that contains base uri and key as global variable. But I got error in line $client. The error is :

syntax error, unexpected '$client' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST)

How to fix it? What wrong with my code?

  • 写回答

1条回答 默认 最新

  • doumou3883 2018-10-27 08:51
    关注

    You can not write any code directly in class definition. You need to define class variable (field) and create instance of class in constructor, eg:

    class Index extends CI_Controller {
    
        use GuzzleHttp\Client;
        protected $client;
    
        public function __construct() {
            parent::__construct();
            $this->load->helper('url');
            $this->client = new Client([    
                'base_uri' => 'https://api.rajaongkir.com/basic/'
            ]); //LINE ERROR
        }
    
        function index() {
            // $client = new GuzzleHttp\Client(['base_uri' => 'https://api.rajaongkir.com/basic/']);
            $key = "b5231ee43b8ee75764bd6a289c4c576d";
            $response = $client->request('GET','province?key='.$key);
            $data['data'] = json_decode($response->getBody());
            $this->load->view('index', $data);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!