Php 如何在CodeIgniter中创建一个全局函数?

Php 如何在CodeIgniter中创建一个全局函数?,php,function,rest,codeigniter,curl,Php,Function,Rest,Codeigniter,Curl,我在我的网站上使用RESTAPI。为此,我必须在每个控制器中多次发出这样的curl请求 $data = array('id' => '01','user_name' => 'abc'); $data_json = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://abc.xyz.com/1.0/index.php/abc_ctrl/function"); curl_setopt($c

我在我的网站上使用RESTAPI。为此,我必须在每个控制器中多次发出这样的curl请求

$data = array('id' => '01','user_name' => 'abc');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://abc.xyz.com/1.0/index.php/abc_ctrl/function");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
$output = curl_exec($ch);
curl_close($ch);
$output3 = json_decode($output);
每个curl的功能都是相同的,就像它通过向rest控制器发送post数据来进行post调用一样。。。。。 我厌倦了每次都使用相同的行…我想在配置文件或主文件中创建一个post请求函数,它接受参数作为url和post数据并返回输出


所以每次我必须在配置中调用该函数并得到结果…

您可以这样做:

public function FunctionName()
  {
    $data = array('id' => '01','user_name' => 'abc');
    $url = "http://abc.xyz.com/1.0/index.php/abc_ctrl/function";
    $result = $this->CurlAPI($data,$url);
  }

  public function CurlAPI($data,$url)
  {
    $data_json = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
    $output = curl_exec($ch);
    curl_close($ch);
    $output3 = json_decode($output);
    return $output3;
  }
更新:

您也可以在助手文件中编写此函数,如下所示:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


    public function CurlAPI($data,$url)
      {
        $data_json = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
        $output = curl_exec($ch);
        curl_close($ch);
        $output3 = json_decode($output);
        return $output3;
      }
也许有趣?可能重复的
$this->load->helper('new_helper');

echo CurlAPI($data,$url);