Multiple API Calls in a Class

后端 未结 3 739
情话喂你
情话喂你 2020-12-20 05:29

I am trying to make multiple API requests and I have to make the request in different functions that are within a class like so:

class exampleClass
{    
  f         


        
3条回答
  •  猫巷女王i
    2020-12-20 06:20

    You are making two API calls, but you don't have to.

    You can put the contents of a call into a member variable in the class with a default value of NULL, and if you want, you can check if that member variable is NULL before making an API call. For example;

    class exampleClass
    {
        private $api_json = NULL;
    
        private function call_api()
        {
            if(is_null($this->api_json))
            {
                $json = // result of api call;
                $this->api_json = $json;
            }
    
            return $this->api_json;
        }
    
        public function printStuffOut() {
            $jsonStuff = $this->call_api();
            $jsonStuff->{'result'}[0]->{'fieldName'};
        }
    
        public function printStuffOut2() {
            $jsonStuff = $this->call_api();
            $jsonStuff->{'result'}[0]->{'fieldName'};
        }
    }
    

提交回复
热议问题