【问题标题】:Consume REST API using Guzzle 6使用 Guzzle 6 使用 REST API
【发布时间】:2018-10-27 16:51:21
【问题描述】:

我尝试使用 Guzzle 6 使用 REST API。我阅读了 Guzzle 的文档,并获得了使用 REST API 的方法,如下所示:

<?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);
    }
}

如果我在函数 index() 中声明变量 $client 就没有问题。我得到了 JSON,我成功地显示在我的视图中。 我只想声明一次 base urikey 并且我可以将 base urikey 用于我的所有功能有。

所以我尝试将包含 base urikey 的变量声明为全局变量。但我在 $client 行出现错误。错误是:

语法错误,意外的 '$client' (T_VARIABLE),期望函数 (T_FUNCTION) 或 const (T_CONST)

如何解决?我的代码有什么问题?

【问题讨论】:

    标签: php codeigniter guzzle


    【解决方案1】:

    您不能直接在类定义中编写任何代码。 您需要定义类变量(字段)并在构造函数中创建类的实例,例如:

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多