致命错误:未捕获错误:调用成员函数getTemperature()

时间:2018-04-07 13:57:37

标签: php

我正在尝试使用此功能,但不断收到错误消息:

  

在网页上编辑文件后,唯一显示的是" ["。

任何人都可以告诉我如何解决我的问题。 我是一名学生,我不是很有经验。这是我的代码:

    <?php
    include('forecast.io.php');
    $apiKeyParam = $_GET["apiKey"];
    $latParam = $_GET["lat"];
    $lonParam = $_GET["lon"];
    $unitsParam = $_GET["units"];
    $langParam = (isset($_GET["lang"]) ? $_GET["lang"] : null);
    $units = 'us';  // Can be set to 'us', 'si', 'ca', 'uk' or 'auto' (see forecast.io API); default is auto
    $lang = 'en'; // Can be set to 'en', 'de', 'pl', 'es', 'fr', 'it', 'tet' or 'x-pig-latin' (see forecast.io API); default is 'en'
    if($unitsParam != "") {
            $units = $unitsParam;
    }
    if($langParam != "") {
            $lang = $langParam;
    }
    //error_log(date(DATE_RFC822)." -- api=".$apiKeyParam.",lat=".$latParam.",lon=".$lonParam.",units=".$units.",lang=".$lang."\n", 3, '/home/weather.log');
    $forecast = new ForecastIO($apiKeyParam, $units, $lang);
    $condition = $forecast;
    echo "CURRENT_TEMP=".round($condition->getTemperature())."\n";
    echo "CURRENT_HUMIDITY=".($condition->getHumidity()*100)."\n";
    echo "CURRENT_ICON=".($condition->getIcon())."\n";
    echo "CURRENT_SUMMARY=".$condition->getSummary()."\n";
    $conditions_week = $forecast->getForecastWeek($latParam, $lonParam);
    echo "MAX_TEMP_TODAY=".round($conditions_week[0]->getMaxTemperature()) . "\n";
    echo "MIN_TEMP_TODAY=".round($conditions_week[0]->getMinTemperature()) . "\n";
    echo "ICON_TODAY=".$conditions_week[0]->getIcon()."\n";
    echo "SUMMARY_TODAY=".$conditions_week[0]->getSummary()."\n";
    echo "MAX_TEMP_TOMORROW=" . round($conditions_week[1]->getMaxTemperature()) . "\n";
    echo "ICON_TOMORROW=".$conditions_week[1]->getIcon()."\n";
    echo "MIN_TEMP_TOMORROW=".round($conditions_week[1]->getMinTemperature()) . "\n";
    echo "SUMMARY_TODAY=".$conditions_week[1]->getSummary()."\n";
    ?> 

这是我的forecast.io.php:

   <?php
   /**
   * Helper Class for forecast.io webservice
   */
   class ForecastIO
   {
   private $api_key;
   private $units;
   private $language;
   const API_ENDPOINT ='https://darksky.net/forecast/53.2789,-9.0109/uk12/en';
/**
 * Create a new instance
 *
 * @param String $api_key
 * @param String $units
 * @param String $language
 */
function __construct($api_key, $units = 'auto', $language = 'en')
{
    $this->api_key = $api_key;
    $this->units = $units;
    $this->language = $language;
}
/**
 * @return string
 */
public function getUnits()
{
    return $this->units;
}
/**
 * @param string $units
 */
public function setUnits($units)
{
    $this->units = $units;
}
/**
 * @return string
 */
public function getLanguage()
{
    return $this->language;
}
/**
 * @param string $language
 */
public function setLanguage($language)
{
    $this->language = $language;
}
private function requestData($latitude, $longitude, $timestamp = false, $exclusions = false)
{
    $validUnits = array('auto', 'us', 'si', 'ca', 'uk');
    if (in_array($this->units, $validUnits)) {
        $request_url = self::API_ENDPOINT .
            $this->api_key . '/' .
            $latitude . ',' . $longitude .
            ($timestamp ? ',' . $timestamp : '') .
            '?units=' . $this->units . '&lang=' . $this->language .
            ($exclusions ? '&exclude=' . $exclusions : '');
        /**
         * Use Buffer to cache API-requests if initialized
         * (if not, just get the latest data)
         *
         * More info: http://git.io/FoO2Qw
         */
        if (class_exists('Buffer')) {
            $cache = new Buffer();
            $content = $cache->data($request_url);
        } else {
            $content = file_get_contents($request_url);
        }
    } else {
        return false;
    }
    if (!empty($content)) {
        return json_decode($content);
    } else {
        return false;
    }
}
/**
 * Will return the current conditions
 *
 * @param float $latitude
 * @param float $longitude
 * @return \ForecastIOConditions|boolean
 */
public function getCurrentConditions($latitude, $longitude)
{   
    $data = $this->requestData($latitude, $longitude);
}
/**
 * Will return historical conditions for day of given timestamp
 *
 * @param float $latitude
 * @param float $longitude
 * @param int $timestamp
 * @return \ForecastIOConditions|boolean
 */
public function getHistoricalConditions($latitude, $longitude, $timestamp)
{
    $exclusions = 'currently,minutely,hourly,alerts,flags';
    $data = $this->requestData($latitude, $longitude, $timestamp, $exclusions);
    if ($data !== false) {
        return new ForecastIOConditions($data->daily->data[0]);
    } else {
        return null;
    }
}
/**
 * Will return conditions on hourly basis for today
 *
 * @param type $latitude
 * @param type $longitude
 * @return \ForecastIOConditions|boolean
 */
public function getForecastToday($latitude, $longitude)
{
    $data = $this->requestData($latitude, $longitude);
    if ($data !== false) {
        $conditions = array();
        $today = date('Y-m-d');
        foreach ($data->hourly->data as $raw_data) {
            if (date('Y-m-d', $raw_data->time) == $today) {
                $conditions[] = new ForecastIOConditions($raw_data);
            }
        }
        return $conditions;
    } else {
        return false;
    }
}
/**
 * Will return daily conditions for next seven days
 *
 * @param float $latitude
 * @param float $longitude
 * @return \ForecastIOConditions|boolean
 */
public function getForecastWeek($latitude, $longitude)
{
    $data = $this->requestData($latitude, $longitude);
    if ($data !== false) {
        $conditions = array();
        foreach ($data->daily->data as $raw_data) {
            $conditions[] = new ForecastIOConditions($raw_data);
        }
        return $conditions;
    } else {
        return false;
    }
}
 }
 /**
* Wrapper for get data by getters
  */
class ForecastIOConditions
{
 private $raw_data;
 function __construct($raw_data)
 {
     $this->raw_data = $raw_data;
 }
 /**
   * Will return the temperature
   *
  * @return String
 */
function getTemperature()
{
    return $this->raw_data->temperature;
}
/**
 * get the min temperature
 *
 * only available for week forecast
 *
 * @return type
 */
function getMinTemperature()
{
    return $this->raw_data->temperatureMin;
}
/**
 * get max temperature
 *
 * only available for week forecast
 *
 * @return type
 */
function getMaxTemperature()
{
    return $this->raw_data->temperatureMax;
}
/**
 * get apparent temperature (heat index/wind chill)
 *
 * only available for current conditions
 *
 * @return type
 */
function getApparentTemperature()
{
    return $this->raw_data->apparentTemperature;
}
/**
 * Get the summary of the conditions
 *
 * @return String
 */
function getSummary()
{
    return $this->raw_data->summary;
}
/**
 * Get the icon of the conditions
 *
 * @return String
 */
function getIcon()
{
    return $this->raw_data->icon;
}
/**
 * Get the time, when $format not set timestamp else formatted time
 *
 * @param String $format
 * @return String
 */
function getTime($format = null)
{
    if (!isset($format)) {
        return $this->raw_data->time;
    } else {
        return date($format, $this->raw_data->time);
    }
}
/**
 * Get the pressure
 *
 * @return String
 */
function getPressure()
{
    return $this->raw_data->pressure;
}
/**
 * Get the dew point
 *
 * Available in the current conditions
 *
 * @return String
 */
function getDewPoint()
{
    return $this->raw_data->dewPoint;
}
/**
 * get humidity
 *
 * @return String
 */
function getHumidity()
{
    return $this->raw_data->humidity;
}
/**
 * Get the wind speed
 *
 * @return String
 */
function getWindSpeed()
{
    return $this->raw_data->windSpeed;
}
/**
 * Get wind direction
 *
 * @return type
 */
function getWindBearing()
{
    return $this->raw_data->windBearing;
}
/**
 * get precipitation type
 *
 * @return type
 */
function getPrecipitationType()
{
    return $this->raw_data->precipType;
}
/**
 * get the probability 0..1 of precipitation type
 *
 * @return type
 */
function getPrecipitationProbability()
{
    return $this->raw_data->precipProbability;
}
/**
 * Get the cloud cover
 *
 * @return type
 */
function getCloudCover()
{
    return $this->raw_data->cloudCover;
}
/**
 * get sunrise time
 *
 * only available for week forecast
 *
 * @param String $format String to format date pph date
 *
 * @return type
 */
function getSunrise($format = null)
{
    if (!isset($format)) {
        return $this->raw_data->sunriseTime;
    } else {
        return date($format, $this->raw_data->sunriseTime);
    }
}
/**
 * get sunset time
 *
 * only available for week forecast
 *
 * @param String $format String to format date pph date
 *
 * @return type
 */
function getSunset($format = null)
{
    if (!isset($format)) {
        return $this->raw_data->sunsetTime;
    } else {
        return date($format, $this->raw_data->sunsetTime);
    }
  }
}

我哪里错了?第19行导致了这个问题。

2 个答案:

答案 0 :(得分:0)

在您的代码方法中,getCurrentConditions是一个void方法,不会返回任何内容。将方法内容更新为与getHistoricalConditions类似的内容,您可以在其中实例化ForecastIOConditions类并将其返回。

请注意,除非保证方法返回值,否则您的代码可能仍会失败,您应将其包装在if语句中。

$condition = $forecast->getCurrentConditions($latParam, $lonParam);

if ($condition) {
    echo "CURRENT_TEMP=".round($condition->getTemperature())."\n";
}

答案 1 :(得分:0)

第(18)行:

$condition = $forecast->getCurrentConditions($latParam, $lonParam);

应该返回定义上方注释块中承诺的class ForecastIOConditions实例。目前,对成员函数getTemperature的调用不会导致错误。

根据编辑问题编辑:

这些行:

$forecast = new ForecastIO($apiKeyParam, $units, $lang);
$condition = $forecast->getCurrentConditions($latParam, $lonParam);
echo "CURRENT_TEMP=".round($condition->getTemperature())."\n";

仍然是错的。 $forecast现在包含ForecastIO的实例,这是$forecast->getCurrentConditions(...)应返回的内容。因此,为了使您的代码更进一步,请将上面的第二行更改为:

$condition = $forecast

一旦你有了工作,你就修复getCurrentConditions(..)使其返回ForecastIO的实例。