无法识别变量内部函数

问题描述 投票:1回答:1

我正在尝试在函数中传递变量以在URL中回显时进行解析,但是我收到错误消息,指出未定义。变量$ plex_token。

function getPlexXML($url)
{
libxml_use_internal_errors(true);
$plex_token = 'xxxxxxxxxx';
$xml = simplexml_load_file($url);
$count = number_format((float)$xml['totalSize']);

if (false === $xml) {
    echo '<div class="counter_offline">N/A</div>';
} else {
    echo '<div class="counter_live">'.$count.'</div>';
}
}

echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');
php function variables
1个回答
1
投票

这是因为您在定义它的上下文之外引用$ plex_token。

您在函数“ getPlexXML”内定义了它,但随后在该函数外使用了它作为传递到getPlexXML的参数。

您可以执行以下任一操作:

A)在函数外部定义它,因为您没有在函数中使用它:

$plex_token = 'xxxxxxxxx';

function getPlexXML($url){
      // You cannot use $plex_token in here
      ...
}

echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');

OR B)将其设为全局变量,然后可以在函数内部或外部使用它:

$plex_token = 'xxxxxxxxx';

function getPlexXML($url){
     global $plex_goken;
     // You can use $plex_token in here
     ...
}
echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');
© www.soinside.com 2019 - 2024. All rights reserved.