如何在不编写新函数的情况下从另一个文件中调用变量


How can I call a variable from another file without writing new function

如何从另一个文件中调用变量?函数是否可以返回5个值?在我的function.php文件中,我在不同的变量中获取了很多值。例如,让我们看看下面的函数
Function.php文件

function getID($url)
{
  global $link;
  $ch = curl_init("http://example.com/?id=".$url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  $raw = curl_exec($ch);
  curl_close($ch);
  $data = json_decode($raw);
  $id=$data->id;
  $cname=$data->name;
  $info=$data->client_info;
  $up=$data->voteup;
  $cat=$data->category;
  return $id;
}

index.php文件

  $myid=getID($url);
  echo "My ID : " . $myid;  -->This is working but not the below four....
  echo "Client Name : "
  echo "Information : "
  echo "Up Votes    : "
  echo "Category    : "

我不想把所有的东西都放在一个文件里。在index.php文件中,我还想在"myid"下输出"cname"、"info"、"up"、"cat"值。我想制作4个不同的函数,并在index.php文件中逐一获取它们。有没有更好的方法,比如getID函数也可以返回其他四个参数,而不是只返回$id?请提供建议。

以数组形式返回数据是的一个选项

function getID($url)
{
global $link;
$ch = curl_init("http://example.com/?id=".$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$raw = curl_exec($ch);
curl_close($ch);
//return the $raw json data as associative array
return json_decode($raw,true);
}
$myinfo=getID($url);
echo "My ID : " . $myinfo['id'];
echo "Client Name : " . $myinfo['client_info'];

等等。。。

只需返回您已经拥有的对象

function getID($url)
{
  $ch = curl_init("http://example.com/?id=".$url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  $raw = curl_exec($ch);
  curl_close($ch);
  return json_decode($raw);
}

然后打电话给

$myid = getID($url);
echo "My ID : " . $myid->id;
echo "Client Name : " . $myid->name;
// etc
相关文章: