dro80463 2018-10-26 23: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 00: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);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部