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);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么