0

如图所示,我的主页包含全球三个城市的天气

索引.php

在主页中,我声明了 3 个变量,用于存储每个城市的 RSS URL

$newYorkWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
$londonWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=UKXX0085&u=c';
$parisWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=FRXX0076&u=c';

我从上面显示的三个 URL 中提取相同的标签,并使用除了传递给它的变量之外的 3 个相同的函数。

下面显示了传递给函数的变量。显然,在返回 $weather 之前使用了其他函数。

function new_york_current_weather($newYorkWeatherSource) {

// Get XML data from source
if (isset($newYorkWeatherSource)) {
    $feed = file_get_contents($newYorkWeatherSource);
} else {
    echo 'Feed not found.  Check URL';
}

checkWeatherFeedExists($feed);
$xml = new SimpleXmlElement($feed);

$weather = get_dateTime($xml);
$weather = get_temperature_and_convert($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);

return $weather;
}

正如我所提到的,我当前重复此函数 3 次,只是替换了上面示例中传递的 $newYorkWeatherSource 变量。有什么想法可以重复使用此功能 3 次,但传递不同的 URL 以保持我的主页显示来自 3 个城市的天气?当然,如果每个城市都在单独的页面上表示,则很容易重用该功能,但目的是将它们放在一起以进行比较。

有任何想法吗?

提前致谢。

4

1 回答 1

2

正如我所提到的,我当前重复此函数 3 次,只是替换了上面示例中传递的 $newYorkWeatherSource 变量。有什么想法可以重复使用此功能 3 次,但传递不同的 URL 以保持我的主页显示来自 3 个城市的天气?

也许我完全错过了您的问题的重点,但是您是在问如何重命名函数和变量吗?因为,如果是这样,这只是在函数的前几行进行搜索和替换的问题......

function get_current_weather($rss_url) {
    // Get XML data from source
    if (isset($rss_url)) {
        $feed = file_get_contents($rss_url);
    } else {
        echo 'Feed not found.  Check URL';
    }
    // ...

只需将特定城市的函数替换为这样开始的函数,然后调用它 3 次,每个特定城市的 RSS 提要 URL 调用一次。


从评论:

但我只是想知道我将如何处理 3 个 RSS URL 变量,因为我无法将它们全部重命名为 $rss_url,因为我只会覆盖它们,直到最终唯一的 URL 将是 Paris

我相信您可能对 PHP 变量范围有误解。让我们以这个片段为例:

function bark($dog) {
    echo 'The dog says ', $dog, ".\n";
}

$cat = 'meow';
bark($cat);

此代码将发出The dog says meow. 当您使用变量调用函数时,PHP 会获取数据*bark的副本并将其作为函数中指定的变量名传递给函数。您不需要在内部和外部将变量命名为相同的东西。事实上,你甚至不能看到在函数之外定义的变量:

function i_see_you() {
    echo 'The dog heard the cat say ', $cat, ".\n";
}
$cat = 'meow';
i_see_you();

此代码将发出The dog heard the cat say .$cat此处超出范围。

回到手头的问题,我们仍然有三个天气 URL。

$newYorkWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
$londonWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=UKXX0085&u=c';
$parisWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=FRXX0076&u=c';

为了使事情正常进行,您需要做的就是:

echo get_current_weather($newYorkWeatherSource);
echo get_current_weather($londonWeatherSource);
echo get_current_weather($parisWeatherSource);

在函数内部,具有正确名称的正确变量将具有正确的数据,并且会发生正确的事情。

*: PHP 使用一种叫做“copy-on-write”的东西,它可以做你认为它可能做的事情。传递包含大数据的变量是完全安全的。它不会消耗意外的内存量。没有必要使用引用。事实上,忘记我曾经说过任何关于引用的事情,你现在不需要它们。
**:可以使用global关键字从全局范围内查看变量。全局变量是不好的做法,会导致意大利面条代码。您可能想阅读更多关于PHP 中变量作用域的信息。

于 2012-01-17T19:46:21.630 回答